簡體   English   中英

我們為什么要使用Object.create?

[英]Why should we use Object.create?

我一直試圖理解為什么我總是在節點上看到這樣的代碼:

var util = require("util");
var events = require("events");

function MyStream() {
    events.EventEmitter.call(this);
}

util.inherits(MyStream, events.EventEmitter);

MyStream.prototype.write = function(data) {
    this.emit("data", data);
}

我去了文檔以便更好地理解。

util.inherits(constructor, superConstructor)

構造函數的原型將設置為從superConstructor創建的新對象。

作為額外的便利,可以通過構造器.super_屬性訪問superConstructor。

util.inherits ,我認為這意味着所有util.inherits都這樣做:

exports.inherits = function (constructor, superConstructor) {
    constructor.super_ = superConstructor;
    constructor.prototype = new superConstructor();
}

似乎對我來說有意義,但是后來我注意到在MyStream構造函數中,它們調用event.EventEmitter.call(this); 這樣EventEmitter構造函數就可以在正在創建的MyStream實例上運行。 自從constructor.prototype = new superConstructor();以來,我對此完全感到困惑constructor.prototype = new superConstructor(); 應該所有需要的對嗎? 好吧,我去了源頭,找到了實際的函數簽名。

exports.inherits = function(ctor, superCtor) {
  ctor.super_ = superCtor;
  ctor.prototype = Object.create(superCtor.prototype, {
    constructor: {
      value: ctor,
      enumerable: false,
      writable: true,
      configurable: true
    }
  });
};

看到這一點后,在試圖弄清Object.create在這里做什么時,我完全感到困惑。 為什么這樣做而不是僅僅使用new superCtor() 我嘗試查看Object.create 的文檔 ,但仍然感到困惑。 讓我嘗試一下,看看我是否可以闡明我的想法 ,而你們可以糾正我:)

Object.create(proto [, propertiesObject ])的第一個參數是您希望此新對象具有的原型。 我想這比定義構造函數和設置其prototype屬性的經典方法容易嗎? 第二個參數是帶有屬性的簡單哈希,應將其添加到將返回的新創建對象中? 所以這...

var myInstance = Object.create(somePrototype, { someProp: someVal, someProp2: someVal2);

...而不是這個?

function MyClass () {
    this.prop = someVal;
    this.prop2 = someVal2;
    // etc
}
MyClass.prototype = somePrototype;
var myInstance = new MyClass();

我不確定我對Object.create理解是否完全准確,因此希望你們能澄清一下。 假設我現在了解Object.create為什么util.inherits函數看起來不是這樣?

exports.inherits = function(ctor, superCtor) {
  ctor.super_ = superCtor;
  ctor.prototype = Object.create(new superCtor, {
    constructor: {
      value: ctor,
      enumerable: false,
      writable: true,
      configurable: true
    }
  });
};

總結

new superCtor消除在MyStream內部執行MyStream events.EventEmitter.call(this)MyStream 為什么如此重要的是我們做原型一樣,然后運行EventEmitter實際實例構造MyStream是創造,而不是僅僅有prototype是一個實際的例子EventEmitter

另外,將constructor屬性添加到ctor的原型的目的是什么? 那是我不了解的JavaScript嗎?

第一父母可能需要參數。 設置Child.prototype時,您正在定義對象,可能尚未准備好創建實例。

第二個父實例的特定值(this.someval)放在孩子的原型上,然后在所有子實例之間共享,或者在Parent.apply(this,arguments)在孩子的身體中執行並對它們進行陰影處理時變得無用。

有關構造函數和原型的更多信息,請參見: https : //stackoverflow.com/a/16063711/1641941

暫無
暫無

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

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