var Object1 = {};
var Object2 = new Object();
var Object3 = Object.create({});
When i check whether the prototype is equal to Object.prototype
:
The first two return true
while the third one returns false
.
Why is this happening?
Object.getPrototypeOf(Object1)===Object.prototype //true
Object.getPrototypeOf(Object2)===Object.prototype //true
Object.getPrototypeOf(Object3)===Object.prototype //false
Simply because if you take a look at the Object.create() in the documentation, you will that this method:
creates a new object with the specified prototype object and properties.
And if you call it with :
Object.create({})
You are not passing a prototype but an empty object with no properties.
So as stated in comments you need to call it like this:
Object.create(Object.prototype)
The Object.create() method creates a new object with the specified prototype object and properties.
Behind the scenes it does the following:
Object.create = (function() {
var Temp = function() {};
return function (prototype) {
if (arguments.length > 1) {
throw Error('Second argument not supported');
}
if (typeof prototype != 'object') {
throw TypeError('Argument must be an object');
}
Temp.prototype = prototype;
var result = new Temp();
Temp.prototype = null;
return result;
};
})();
So the right use would be:
var Object3 = Object.create(Object.prototype);
Or if you want to make your example work:
Object.getPrototypeOf(Object.getPrototypeOf(Object3)) === Object.prototype // true
Here the prototype chain comes into play:
console.dir(Object3)
-> __proto__: Object (=== Your Object Literal)
-> __proto__: Object (=== Object.prototype)
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.