简体   繁体   English

了解原型继承

[英]Understanding Prototypal Inheritance

var Object1 = {};
var Object2 = new Object();
var Object3 = Object.create({});

When i check whether the prototype is equal to Object.prototype : 当我检查原型是否等于Object.prototype

The first two return true while the third one returns false . 前两个返回true而第三个返回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: 只是因为如果你看一下文档中的Object.create() ,你就会知道这个方法:

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. Object.create()方法使用指定的原型对象和属性创建一个新对象。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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