0
根据我的理解(尽管Javascript是新的),Object实例继承了它们原型的属性和方法。在下面,我明确地将Title对象实例的原型设置为Foo()
,因此Title应该继承Foo的属性(bar),但alert(Title.bar);
输出undefined
,而它应该(根据我的理解)输出Vanilla
。很明显,我的理解有些问题,有人可以帮我理解为什么alert(Title.bar);
输出undefined
,而alert(Title.prototype.bar);
输出Vanilla
。对象实例为Prototype的属性输出`undefined`。为什么?
function Foo(name) {
return this.bar = name;
};
Foo.prototype.append = function (what) { return this.bar += "" + what; }
Foo.prototype.newbar = "Chocolate";
function Title() {
return function page_title() { return this.title = this.bar; }
}
//Setting Prototype of Title instance to Foo()
Title.prototype = new Foo('Vanilla');
//Setting Prototype's Constructor to Title() for proper inheritance
Title.prototype.constructor = Title;
//Calling Inherited variable(Prototype's) on the instance
alert(Title.bar); // undefined
出于某种奇怪的原因,你'return'ing从你的'Title'构造函数。您将无法以这种方式创建实例,每次调用“新标题”时,您只会获得一个函数。 – Bergi
'Title'不是一个实例,并且不会从'Title.prototype'继承! – Bergi
我相信'Title'是因为通过定义一个构造函数(Title()),JS会自动创建一个同名的对象。如果我错了,请纠正。 –