简体   繁体   中英

Confused about Douglas Crockford's object function

I know Crockford has a famous object function for inheritance in JavaScript:

function object(o) {
    function F() {}
    F.prototype = o;
    return new F();
}

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

Isn't that common practice?

Isn't that common practice?

Only when your're creating subclasses (constructor functions with prototypes inheriting from other prototypes).

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; 

why he doesn't he do F.prototype.constructor = F ?

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

Since you are using an instance of F as prototype object itself, there is no benefit in setting the constructor property.

For example:

function Foo() {}
function Bar() {}

Bar.prototype = object(Foo.prototype);
Bar.prototype.constructor = Bar;

So now Bar.prototype is an instance of F . We assigned the constructor property to that instance which would shadow the constructor property assigned to F.prototype . So why bother assigning it in the first place?

Generally speaking the constructor property has no significance in JavaScript, but it may be useful in your own code. Ie your code might depend on the correct value of constructor . But in the object function, F is just a temporary constructor and object just replicates the functionality of Object.create , which is supported in newer browsers. I cannot think of a use case where you want a reference to F in your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM