简体   繁体   中英

JavaScript OOP Object.create();

I have heard that the Object.create(); method creates a new object and inherits the PROTOTYPE of the Object that is passed as the first parameter.

However I've seen both of these scenarios:

var newObj = Object.create(BaseObject);

And

var newObj = Object.create(BaseObject.prototype);

The first scenario is inheriting the prototype of BaseObject and the second is doing the same, is there any difference? It seems like no, there is not.

Whatever you pass as the first argument to Object.create will be assigned to the prototype of your new object. So it really depends what BaseObject is, if you have functions defined on BaseObject then the first example is correct, however it is also possible to assign functions to the prototype of BaseObject in which case you should pass the prototype to Object.create .

var BaseObject = {
   doSomething: function() { alert('hi'); }
}

var newObj = Object.create(BaseObject);
newObj.doSomething() // Alerts hi

function BaseObject() {
}

BaseObject.prototype.doSomething = function() { alert('hi'); };

function ChildObject() {
}

ChildObject.prototype = Object.create(BaseObject.prototype);

var newObj = new ChildObject();
newObj.doSomething() // Alerts hi

It depends whether what you are extending is using the prototype and whether you intend to use new when creating objects. As ever MDN has a good example of building an inheritance chain using the prototype and Object.create .

 var newObj = Object.create(BaseObject); 

You use this when you inherit from a single object, which here is located in the variable BaseObject (uncommon casing). More likely, you have seen

var newObj = Object.create(baseObject);
var newObj = Object.create(instanceOfBase);
 var newObj = Object.create(BaseObject.prototype); 

This just does the same, but the object from which your newObj will inherit is located at the .prototype property of BaseObject here. That is the common case for constructor functions:

var newObj = Object.create(BaseConstructor.prototype);

There is no difference in the behaviour of Object.create , only you pass a different argument.


The first scenario is inheriting the prototype of BaseObject

No, it does not. It creates a newObj that does inherit from the BaseObject object itself. If BaseObject is a function, that's likely not to be what you wanted.

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