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

标签 javascript inheritance prototype object-create

我是原型(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/

相关文章:

javascript - 在 Angular Js 中重新加载页面后指令无法调用工厂?

javascript - 从 firebase 获取数据不起作用

javascript - JS变量声明的类型

java - 迁移到 Hibernate 4、@Inheritance 和 @GenerateValue 的误解

javascript - Rails3 link_to :with attribute?

javascript - 谷歌折线图上的额外直线

java - 避免在不同上下文中多次实现同一方法

java - java子类中的共享变量

Javascript、 Node 、Q promises、原型(prototype)函数和 "this"

javascript - 原型(prototype)继承应该节省内存吧?