MDN wants to learn about developers like you: https://qsurvey.mozilla.com/s3/MDN-dev-survey

翻譯不完整。請協助 翻譯此英文文件

Object.create() 指定其原型物件與屬性,創建一個新物件。

語法

Object.create(proto[, propertiesObject])

參數

proto
指定新物件的原型 (prototype) 物件。
propertiesObject
選用,為一物件。如有指定且非 undefined,則此參數物件中可列舉出的屬性 (即參數物件自身定義的屬性,並非指原型鏈上的 enumerable 特性 ) 對應其屬性名稱,根據其屬性敘述元 (property descriptors) 加進新創建的物件。這些屬性對應到 Object.defineProperties() 的第二個參數。

回傳

具有指定原型物件與屬性的新物件。

例外

 如果 proto 參數不是 null 或一個物件,將會拋出 TypeError 例外。

範例

使用 Object.create() 實現類別繼承

下方是如何使用 Object.create() 去實現類別繼承的示範,此為 JavaScript 支援的單一繼承.。

// Shape - 超類別
function Shape() {
  this.x = 0;
  this.y = 0;
}

// 超類別的方法
Shape.prototype.move = function(x, y) {
  this.x += x;
  this.y += y;
  console.info('Shape moved.');
};

// Rectangle - 子類別
function Rectangle() {
  Shape.call(this); // call super constructor.
}

// 子類別擴展(extends)超類別
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;

var rect = new Rectangle();

console.log('Is rect an instance of Rectangle?', rect instanceof Rectangle);// true
console.log('Is rect an instance of Shape?', rect instanceof Shape);// true
rect.move(1, 1); // Outputs, 'Shape moved.'

若想繼承多物件時,可使用 mixin。

function MyClass() {
  SuperClass.call(this);
  OtherSuperClass.call(this);
}

MyClass.prototype = Object.create(SuperClass.prototype); // inherit
mixin(MyClass.prototype, OtherSuperClass.prototype); // mixin

MyClass.prototype.myMethod = function() {
  // do a thing
};

The mixin function would copy the functions from the superclass prototype to the subclass prototype, the mixin function needs to be supplied by the user. An example of a mixin like function would be jQuery.extend().

propertiesObject 參數的使用

var o;

// 建立以null為原型的物件
o = Object.create(null);


o = {};
// 等同於:
o = Object.create(Object.prototype);


// Example where we create an object with a couple of sample properties.
// (Note that the second parameter maps keys to *property descriptors*.)
o = Object.create(Object.prototype, {
  // foo 為數值屬性
  foo: { writable: true, configurable: true, value: 'hello' },
  // bar 為 getter-and-setter 訪問屬性
  bar: {
    configurable: false,
    get: function() { return 10; },
    set: function(value) { console.log('Setting `o.bar` to', value); }
/* with ES5 Accessors our code can look like this
    get function() { return 10; },
    set function(value) { console.log('setting `o.bar` to', value); } */
  }
});


function Constructor() {}
o = new Constructor();
// 等同於:
o = Object.create(Constructor.prototype);
// Of course, if there is actual initialization code in the
// Constructor function, the Object.create() cannot reflect it


// 創建一個新物件,指定原型是全新的空物件,並加入值為 42 的屬性'p'
o = Object.create({}, { p: { value: 42 } });

// 屬性敘述元 writable, enumerable , configurable 未定義,預設皆為 false
o.p = 24;
o.p;
// 42

o.q = 12;
for (var prop in o) {
  console.log(prop);
}
// 'q'

delete o.p;
// false

// to specify an ES3 property
o2 = Object.create({}, {
  p: {
    value: 42,
    writable: true,
    enumerable: true,
    configurable: true
  }
});

Polyfill

This polyfill covers the main use case which is creating a new object for which the prototype has been chosen but doesn't take the second argument into account.

Note that while the setting of null as [[Prototype]] is supported in the real ES5 Object.create, this polyfill cannot support it due to a limitation inherent in versions of ECMAScript lower than 5.

if (typeof Object.create != 'function') {
  Object.create = (function(undefined) {
    var Temp = function() {};
    return function (prototype, propertiesObject) {
      if(prototype !== Object(prototype) && prototype !== null) {
        throw TypeError('Argument must be an object, or null');
      }
      Temp.prototype = prototype || {};
      if (propertiesObject !== undefined) {
        Object.defineProperties(Temp.prototype, propertiesObject);
      } 
      var result = new Temp(); 
      Temp.prototype = null;
      // to imitate the case of Object.create(null)
      if(prototype === null) {
         result.__proto__ = null;
      } 
      return result;
    };
  })();
}

規範

Specification Status Comment
ECMAScript 5.1 (ECMA-262)
The definition of 'Object.create' in that specification.
Standard Initial definition. Implemented in JavaScript 1.8.5.
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'Object.create' in that specification.
Standard  
ECMAScript Latest Draft (ECMA-262)
The definition of 'Object.create' in that specification.
Living Standard  

瀏覽器相容性

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 5 4.0 (2) 9 11.60 5
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (Yes) (Yes) 4.0 (2) (Yes) 11.5 (Yes)

參閱

文件標籤與貢獻者

 此頁面的貢獻者: yuugou727, septemhill, jackblackevo
 最近更新: yuugou727,