【问题标题】:Constructor-Prototype cyclic reference JavaScriptConstructor-Prototype 循环引用 JavaScript
【发布时间】:2015-03-18 07:09:07
【问题描述】:

我正在写一篇关于函数对象的constructor 属性的博客,并遇到了这一行:

函数对象的原型属性将构造函数属性设置为函数本身

意思是,下面的函数对象

function Student(name,age) {
    this.name = name;
    this.age = age;
}

会有以下原型

{constructor : Student}

    function Student() {
    }

    console.log(Student.prototype);
    console.log(Student.prototype.constructor);
    console.log(Student.prototype.constructor.prototype);
    console.log(Student.prototype.constructor.prototype.constructor);
    console.log(Student.prototype.constructor.prototype.constructor.prototype);

这意味着原型具有constructor 属性,该属性设置为具有相同原型对象的函数本身。这是否有某些原因,或者它只是一个语言功能。我找不到任何理由在这里进行循环引用。

任何帮助表示赞赏。谢谢。

【问题讨论】:

  • 这是一个有趣的问题。不过这对我来说很有意义。它是一个用户定义的函数,所以它的原型就是它自己。由于用户在全局命名空间中定义的上下文,构造函数也将是其自身。
  • “我找不到任何理由在这里进行循环引用。” --- 你会怎么设计呢?
  • 是的,除非您从Student 返回this,否则不会导致循环引用错误。
  • @Madhu 怎么会导致报错?构造函数的返回值实际上被忽略了,jsfiddle

标签: javascript constructor prototype


【解决方案1】:

prototype.constructor 属性设置为引用构造函数,以便由该构造函数实例化的对象可以检查使用哪个构造函数创建它们。

【讨论】:

    【解决方案2】:

    是的,这只是一个语言功能。还有一个非常有用的:

    • 构造函数上的.prototype 引用用于在使用new 创建新实例时设置继承
    • 原型上的.constructor 引用可用于从实例访问“类”,例如创建克隆、重新初始化实例、访问类名或仅用于检查值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-02
      • 2016-03-22
      • 1970-01-01
      • 2019-06-14
      • 1970-01-01
      相关资源
      最近更新 更多