【发布时间】:2015-12-18 11:40:24
【问题描述】:
根据我的理解(虽然是 Javascript 的新手),Object 实例继承其原型的属性和方法。在下文中,我将 Title 对象实例的原型显式设置为 Foo(),因此 Title 应该继承 Foo 的属性(bar)但 alert(Title.bar); 输出 undefined 而它应该(根据我的理解)输出 Vanilla。显然我的理解有问题,有人能帮我理解为什么alert(Title.bar); 输出undefined 而alert(Title.prototype.bar); 输出Vanilla。
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
【问题讨论】:
-
出于某种奇怪的原因,您正在
returning 来自您的Title构造函数的函数。您将无法以这种方式创建实例,每次调用new Title时,您只会获得一个函数。 -
Title不是实例,也不继承自Title.prototype! -
我相信
Title是因为通过定义构造函数(Title()),JS自动创建了一个同名对象。如果我错了,请纠正。 -
是的,当你声明
Title时,JS确实会创建一个构造函数对象(继承自Function.prototype)。但它不会实例化Title实例。您需要为此执行new Title(如果有效,请参阅我的第一条评论)
标签: javascript constructor function-prototypes