构造函数原型循环参考JavaScript [英] Constructor-Prototype cyclic reference JavaScript

查看:86
本文介绍了构造函数原型循环参考JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用函数对象的构造函数的属性撰写博客,并碰到了这一行:


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


含义是以下函数对象

 函数Student(name,age){
this.name = name;
this.age =年龄;
}

将具有以下原型



{构造函数:学生}



 函数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);  



表示原型具有构造函数属性,该属性设置为具有相同原型对象的函数本身。是因为某些原因还是仅仅是语言功能。我找不到在此处进行循环引用的任何理由。



任何帮助表示感谢。谢谢。

解决方案

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




  • 使用构造函数上的 .prototype 引用在使用 new

  • .constructor 原型上的引用可用于从实例访问类,例如创建克隆,重新初始化实例,访问类名,或仅用于检查值。


I was working a blog on constructor property of a function object and came across this line:

The prototype property of a function Object has the constructor property set to the function itself

Meaning, the following function object

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

will have the following prototype

{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);

which means the prototype has the constructor property which is set to the function itself that has the same prototype object. Does this have some reasons or it was just a language feature. I couldn't find any reason for having circular reference here.

Any help appreciated. Thanks.

解决方案

Yes, this is just a language feature. And a pretty useful one:

  • the .prototype reference on the constructor is used to set up inheritance when creating a new instance with new
  • the .constructor reference on the prototype can be used to access the "class" from the instance, e.g. to create a clone, to re-initialise the instance, to access the class name, or just for checking the value.

这篇关于构造函数原型循环参考JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆