【问题标题】:Prototypal inheritance: Can you chain Object.create?原型继承:你能链接 Object.create 吗?
【发布时间】:2010-02-19 16:56:05
【问题描述】:

我是原型继承的新手,所以我试图理解“正确”的方式。我想我可以这样做:

if (typeof Object.create !== 'function') {
    Object.create = function (o) {
        function F() {}
        F.prototype = o;
        return new F();
    };
}

var tbase = {};

tbase.Tdata = function Tdata() {};

tbase.Tdata.prototype.say = function (data) {
    console.log(data);
};

var tData = new tbase.Tdata();

tbase.BicData = Object.create(tData);

tbase.BicData.prototype.say = function (data) {
    console.log("overridden: " + data)
};

tbase.BicData.prototype.shout = function (data, temp) {
    console.log("SHOUT: " + data + ", " + temp)
};

var test = new tbase.BicData();

tData.say("test1"); 
test.say("test2");
test.shout("test3", "hope");

if (typeof Object.create !== 'function') {
    Object.create = function (o) {
        function F() {}
        F.prototype = o;
        return new F();
    };
}

var tbase = {};

tbase.Tdata = function Tdata() {};

tbase.Tdata.prototype.say = function (data) {
    console.log(data);
};

var tData = new tbase.Tdata();

tbase.BicData = Object.create(tData);

tbase.BicData.prototype.say = function (data) {
    console.log("overridden: " + data)
};

tbase.BicData.prototype.shout = function (data, temp) {
    console.log("SHOUT: " + data + ", " + temp)
};

var test = new tbase.BicData();

tData.say("test1"); 
test.say("test2");
test.shout("test3", "hope");

但我却得到“tbase.BicData.prototype is undefined”

在 Java 中,我想要将 Tdata 作为样板“接口”,将 BicData 作为其实现,然后从它。

我哪里错了?

【问题讨论】:

    标签: javascript inheritance prototype object-create


    【解决方案1】:

    问题在于tbase.BicData是一个对象(tbase.BicData = Object.create(tData);),而prototype属性应该用在构造函数上。

    利用Object.create 方法,我会做这样的事情:

    var tbase = {};
    
    tbase.Tdata = {
      say : function (data) {
        console.log(data);
      }
    };
    
    tbase.BicData = Object.create(tbase.Tdata);
    
    tbase.BicData.say = function (data) {
        console.log("overridden: " + data)
    };
    
    tbase.BicData.shout = function (data, temp) {
        console.log("SHOUT: " + data + ", " + temp)
    };
    
    var test = Object.create(tbase.BicData);
    var tData = Object.create(tbase.Tdata);
    
    tData.say("test1"); // test1
    test.say("test2"); // overridden: test2
    test.shout("test3", "hope"); // SHOUT: test3, hope
    

    【讨论】:

    • 我认为,如果 OP 没有混合 new 和 Object.create,大部分 OP 的混淆都可以避免。我说选择一个并坚持下去。
    猜你喜欢
    • 2011-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-09
    • 2012-06-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多