困惑关于道格拉斯Crockford的对象函数 [英] Confused about Douglas Crockford's object function
问题描述
我知道Crockford在JavaScript中有一个着名的对象函数用于继承:
I know Crockford has a famous object function for inheritance in JavaScript:
function object(o) {
function F() {}
F.prototype = o;
return new F();
}
但我很困惑,行后 prototype = o
,为什么他不重置 F.prototype
的构造函数,如下所示:
But I am confused, after the line F.prototype = o
, why he doesn't he reset the F.prototype
's constructor, like this:
F.prototype.constructor = F
这不是常见的做法吗? / p>
Isn't that common practice?
推荐答案
这不是常见的做法吗?
Isn't that common practice?
只有当你创建子类(构造函数,原型继承自其他原型)。
Only when your're creating subclasses (constructor functions with prototypes inheriting from other prototypes).
但这不是目的此代码基本上 Object.create
。它需要创建从另一个对象继承的对象的一部分,没有别的。 F
构造函数只是中间的,不应该被暴露。
But that's not the purpose of this code, which basically Object.create
. It takes the part of creating the object which inherits from another object, nothing else. The F
constructor function is only intermediate and not supposed to be exposed.
F.prototype = o;
为什么他不做 F.prototype.constructor = F
?
why he doesn't he do F.prototype.constructor = F
?
因为这会改变 o
目的只是创建一个新对象。请注意,它会返回中间构造函数的实例,而不是构造函数本身。
Because that would change o
itself. The aim is only to create a new object. Notice that it returns an instance of the intermediate constructor, not the constructor itself.
将构造函数
设置(如果需要)?在由对象实例化的新对象上:
Where would the constructor
be set (if needed)? On the new object that is instantiated by object
:
function inherit(chd, par) {
chd.prototype = object(par.prototype);
chd.prototype.constructor = chd;
}
function Foo() {}
function Bar() {}
inherit(Foo, Bar);
/* Because of overwriting `constructor`: */
Foo.prototype.constructor === Foo
(new Foo).constructor === Foo
/* Because of the prototype chain: */
new Foo instanceof Bar // true, because
Foo.prototype instanceof Bar // true
这篇关于困惑关于道格拉斯Crockford的对象函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!