gpt4 book ai didi

javascript - 原型(prototype)继承: Can you chain Object.创建?

转载 作者:数据小太阳 更新时间:2023-10-29 05:13:54 26 4
gpt4 key购买 nike

我是原型(prototype)继承的新手,所以我想了解“正确”的方式。我以为我可以这样做:

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 作为样板“接口(interface)”,将 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) {
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

关于javascript - 原型(prototype)继承: Can you chain Object.创建?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2298103/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com