2015-12-18 85 views
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 
+2

出于某种奇怪的原因,你'return'ing从你的'Title'构造函数。您将无法以这种方式创建实例,每次调用“新标题”时,您只会获得一个函数。 – Bergi

+2

'Title'不是一个实例,并且不会从'Title.prototype'继承! – Bergi

+0

我相信'Title'是因为通过定义一个构造函数(Title()),JS会自动创建一个同名的对象。如果我错了,请纠正。 –

回答

0

,你可以把它叫做redirection(重定向),但它可以通过这种方式来完成:

Title.prototype =新的Foo( “香草”);

然后创建另一个实例即

VAR REK = Title.prototype

现在检查REK的instanceof富REK的instanceof富 它会给你的实例更好的了解

alert(rek.bar)//给你的香草

:)

相关问题