本文介绍了为什么要在OOP javascript中使用object.prototype.constructor?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始阅读OOP javascript,作者似乎跳过的一件事是当声明了对象A时,突然我看到"A.prototype.constructor = A;例如

I've recently started reading up on OOP javascript and one thing that authors seem to skip over is when an object A has been declared and suddenly I see "A.prototype.constructor =A; For example,

var A = function(){}; // This is the constructor of "A"
A.prototype.constructor = A;
A.prototype.value = 1;
A.prototype.test = function() { alert(this.value); }
var a = new A(); // create an instance of A
alert(a.value);  // => 1

因此,我在萤火虫中运行命令"var A = function(){};"然后显示"A.Constructor",它是一个函数.我了解这一点.
我运行代码"A.prototype.constructor = A;"并且我认为这会将A构造函数从Function更改为A.

So I run the command in firebug "var A = function(){};" and then "A.Constructor" Which reveals it's a function. I understand this.
I run the code "A.prototype.constructor = A;" and I thought this changes the A constructor from Function to A.

A的构造函数属性已更改,对吗?相反,当我运行"A.constructor"时,它仍然给我函数().

The constructor property of A has been changed right? Instead when I run "A.constructor" it gives me function () still.

有什么意义?

我还看到了A.constructor.prototype.constructor.prototype ..这是怎么回事?

I also see A.constructor.prototype.constructor.prototype.. what is going on?

推荐答案

如果A使用A.prototype = new B();继承B,则需要使用A.prototype.constructor=A;重置类A的构造函数属性,否则A的实例将具有构造函数的B.

If A inherit B using A.prototype = new B();, you need to reset the constructor property for the class A using A.prototype.constructor=A;, otherwise instances of A would have a constructor of B.

在您的情况下,A.prototype.constructor === A将返回true,因此A.prototype.constructor = A什么也不做.

In your case, A.prototype.constructor === A will return true, so A.prototype.constructor = A did nothing.

这篇关于为什么要在OOP javascript中使用object.prototype.constructor?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 02:38