Object.create(Object.prototype)vs var task = Object.create(Object)

时间:2018-03-31 09:29:27

标签: javascript object prototype

在创建新对象时,我们为什么要使用

var task = Object.create(Object.prototype);               代替 , var task = Object.create(Object);

1 个答案:

答案 0 :(得分:0)

MDN Object.create()中,有两个示例:

const me = Object.create(person)

Rectangle.prototype = Object.create(Shape.prototype)

我将它们合并为一个样本:

function Shape() {
  this.x = 0;
  this.y = 0;
  this.speak = function() {
    console.log("this is an instance function")
  }
}
// Shape.speak = ...

Shape.prototype.move = function(x, y) {
  this.x += x;
  this.y += y;
  console.info('this is a prototype function');
};

function Rectangle() { Shape.call(this); }
function Triangle() { Shape.call(this); }

Rectangle.prototype = Object.create(Shape.prototype);
Triangle.prototype = Object.create(Shape);

var rect = new Rectangle();
var tri = new Triangle();

rect.constructor // f Shape
tri.constructor // f Function

rect.speak // f speak
tri.speak // f speak

rect.move // f move
tri.move // undefined, could not access methods in Shape.prototype

Rectangle.prototype = Object.create(Shape.prototype)的结果为rect.__proto__.__proto__ === Shape.prototype

Triangle.prototype = Object.create(Shape)的结果为tri.__proto__.__proto__ === Shape

要了解这一点,我们必须了解Object.create() Polyfill

的核心
Object.create = function (proto, propertiesObject) {
  function F() {}
  F.prototype = proto;

  // (new F()).__proto__ === F.prototype === proto
  return new F(); 
};

派生于:

(new F()).__proto__ === F.prototype === Shape.prototype
Rectangle.prototype === new F()
rect.__proto__.__proto__ === Rectangle.prototype.__proto__  === (new F()).__proto__ === Shape.prototype

(new F()).__proto__ === F.prototype === Shape
Triangle.prototype === new F()
tri.__proto__.__proto__ === (Triangle.prototype).__proto__ === (new F()).__proto__ === Shape