Vaguely about the function of Douglas Crockford's object

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 doesn't it reset the constructor F.prototype

like this:

F.prototype.constructor = F

Isn't this common practice?

0


source to share


2 answers


?

Only when you create subclasses (constructor functions with prototypes inheriting from other prototypes).

But that's not the purpose of this code, which is mostly Object.create

. He takes part in creating an object that inherits from another object and nothing else. The constructor function F

is only intermediate and should not be rendered.

F.prototype = o;

      

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

?



Because it would change itself o

. The goal is to create only a new object. Note that it returns an instance of the intermediate constructor, not the constructor itself.


Where to install constructor

( if necessary )? About the new object being created 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

      

+1


source


Since you are using an instance F

as your prototype object, there is no benefit in setting the property constructor

.

For example:

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

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

      



So now it Bar.prototype

is an instance F

. We assigned this property to a property constructor

that shadows the property constructor

assigned F.prototype

. So why appoint it at all?

Generally speaking, the property constructor

is irrelevant in JavaScript, but it can be useful in your own code. That is, your code may depend on the correct value constructor

. But the object

function F

is only a temporary constructor, it object

simply replicates functionality Object.create

that is supported in new browsers. I can't think of a use case where you want to link to F

in your code.

0


source







All Articles