【问题标题】:Object instance outputs `undefined` for it's Prototype's property. Why?对象实例为它的原型属性输出“未定义”。为什么?
【发布时间】: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


【解决方案1】:

您可以将其称为重定向,但可以使用这种方式完成:

Title.prototype = new Foo("Vanilla");

然后创建另一个实例,即

var rek = Title.prototype

现在检查 rek instanceof Foo 和 rek instanceof Foo 的实例 它会让你更好地理解

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

:)

【讨论】:

    猜你喜欢
    • 2013-01-05
    • 2020-01-05
    • 2020-04-14
    • 2021-11-10
    • 2012-01-10
    • 1970-01-01
    • 1970-01-01
    • 2015-09-16
    • 1970-01-01
    相关资源
    最近更新 更多