Javascript的构造函数属性的意义是什么? [英] What it the significance of the Javascript constructor property?

查看:171
本文介绍了Javascript的构造函数属性的意义是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

< p>尝试在JavaScript的OO之上弯腰...和许多其他人一样,对构造函数属性造成混乱。特别是,构造函数属性的意义,因为我似乎不能使它有任何效果。例如:

  function Foo(age){
this.age = age;
}

function Bar(){
this.name =baz;
}

Bar.prototype = new Foo(42);
var b = new Bar;

alert(b.constructor); //Foo。没关系,因为我们继承了Foo的原型。
alert(b.name); //baz。显示Bar()被称为构造函数。
alert(b.age); //42,继承自`Foo`。在上面的例子中,对象 b Bar )–并从 Foo 继承age属性。所以为什么很多人建议这是一个必要的步骤:

  Bar.prototype.constructor = Bar; 

显然,正确的 Bar > 在构建 b 时被调用,因此这个原型属性有什么影响?我很想知道实际上使构造函数属性设置为正确的实际差异,因为我看不到它对创建对象后实际调用的构造函数有什么影响。

解决方案

构造函数属性在内部绝对没有实际的区别。它只有任何用途,如果你的代码明确使用它。例如,你可能决定你需要每个对象来引用创建它的实际构造函数;如果是这样,在设置继承时,需要通过将一个对象赋值给构造函数的原型来显式地设置构造函数 $ c>属性,如在您的示例中。


Trying to bend by head around Javascript's take on OO...and, like many others, running into confusion about the constructor property. In particular, the significance of the constructor property, as I can't seem to make it have any effect. E.g.:

function Foo(age) {
    this.age = age;
}

function Bar() {
    this.name = "baz"; 
}

Bar.prototype = new Foo(42); 
var b = new Bar;    

alert(b.constructor); // "Foo". That's OK because we inherit `Foo`'s prototype.
alert(b.name);        // "baz". Shows that Bar() was called as constructor.
alert(b.age);         // "42", inherited from `Foo`.

In the above example, the object b seems to have had the right constructor called (Bar) – and it inherits the age property from Foo. So why do many people suggest this as a necessary step:

Bar.prototype.constructor = Bar;

Clearly, the right Bar constructor was called when constructing b, so what impact does this prototype property have? I am curious to know what practical difference it actually makes to have the constructor property set 'correctly'—as I can't see it having any affect on which constructor is actually called after an object is created.

解决方案

The constructor property makes absolutely no practical difference to anything internally. It's only any use if your code explicitly uses it. For example, you may decide you need each of your objects to have a reference to the actual constructor function that created it; if so, you'll need to set the constructor property explicitly when you set up inheritance by assigning an object to a constructor function's prototype property, as in your example.

这篇关于Javascript的构造函数属性的意义是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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