对象实例为其输出“未定义”'s原型'的属性.为什么?

Object instance outputs `undefined` for it's Prototype's property. Why?

本文关键字:未定义 原型 属性 为什么 实例 对象 输出      更新时间:2023-09-26

根据我的理解(虽然是Javascript的新手),对象实例继承其原型的属性和方法。在下文中,我明确地将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

您可以称之为重定向,但可以使用以下方式完成:

Title.protype=新Foo("香草");

然后创建另一个实例,即

var rek=标题原型

现在检查rek instanceofFoorek instance of Foo

alert(rek.bar)//提供香草

:)