簡體   English   中英

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

[英]Object.create(Object.prototype) vs var task=Object.create(Object)

在創建新對象時,為什么使用

var task = Object.create(Object.prototype); 而不是var task = Object.create(Object);

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM