JavaScript   发布时间:2022-04-16  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了javascript – Prototypal继承:你可以链接Object.create吗?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我是原型继承的新手,所以我试图理解’正确’的方式.我以为我能做到这一点:
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,"hope");

但相反,我得到“tbase.bicData.prototype未定义”

在Java中,我想要的是将Tdata作为样板“接口”,将BicData作为其实现,然后从中实例化对象.

我哪里错了?

解决方法

问题是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)
};

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

大佬总结

以上是大佬教程为你收集整理的javascript – Prototypal继承:你可以链接Object.create吗?全部内容,希望文章能够帮你解决javascript – Prototypal继承:你可以链接Object.create吗?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。