共享原型

/**
 * 共享原型
 * 原理: js中对象按引用传递
 */

//facade 一个输出函数
function log() {
    console.log([].join.call(arguments, ','));
}

//第一个类
function One(name) {
    this.name = name || "Adam";
}

//第一个类原型上添加一个方法
One.prototype.say = function() {
    return this.name;
}

//实现共享原型
function share_prototype(one, two) {
    two.prototype = one.prototype;
}

//第二个类
function Two(name) {
    this.name = name;
}

//执行共享原型,注意:这儿传入的是类名,只有类名才可以直接调用prototype
share_prototype(One, Two);

var o = new One("abc    ");
log(o.name);
log(o.say());

var t = new Two("suxiaolin");
log(t.name);
log(t.say());

  

posted on 2013-07-07 22:58  mtima  阅读(181)  评论(0编辑  收藏  举报

导航