了解原型继承

时间:2015-07-22 08:19:50

标签: javascript object inheritance prototypal

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

当我检查原型是否等于Object.prototype

前两个返回true,而第三个返回false

为什么会这样?

Object.getPrototypeOf(Object1)===Object.prototype //true
Object.getPrototypeOf(Object2)===Object.prototype //true
Object.getPrototypeOf(Object3)===Object.prototype //false

2 个答案:

答案 0 :(得分:2)

只是因为如果您查看文档中的Object.create(),那么您将采用以下方法:

  

使用指定的原型对象创建一个新对象   属性。

如果你打电话给:

Object.create({})

您没有传递原型,而是传递没有属性的空对象。

正如评论中所述,您需要这样称呼它:

Object.create(Object.prototype)

答案 1 :(得分:1)

  

Object.create()方法使用指定的原型对象和属性创建一个新对象。

在幕后,它执行以下操作:

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;
  };
})();

所以正确的用途是:

var Object3 = Object.create(Object.prototype);

或者如果你想让你的例子有用:

Object.getPrototypeOf(Object.getPrototypeOf(Object3)) === Object.prototype // true 

这里原型链发挥作用:

console.dir(Object3)
 -> __proto__: Object (=== Your Object Literal)
   -> __proto__: Object (=== Object.prototype)