天天看點

JavaScript之Object.create()方法詳解

​Object.create()​

方法建立一個新對象,使用現有的對象來提供新建立的對象的__proto__。

文法:Object.create(proto[, propertiesObject])  傳回值:一個新對象,帶着指定的原型對象和屬性。

proto:新建立對象的原型對象。

propertiesObject:可選。如果沒有指定為 undefined,則是要添加到新建立對象的可枚舉屬性(即其自身定義的屬性,而不是其原型鍊上的枚舉屬性)對象的屬性描述符以及相應的屬性名稱。這些屬性對應Object.defineProperties()的第二個參數。如果propertiesObject參數是 null 或非原始包裝對象,則抛出一個 TypeError 異常。

1.方法内部定義一個新的空對象obj 

2.将obj._proto _的對象指向傳入的參數proto 

3.傳回一個新的對象 ;

​Object.create() 和 new Object() 的不同​

new Object()方式建立 

var newObj = {
    name: 'fx',
    why: {
        day: 1
    }
}
var b = new Object(newObj)
console.log(b)
b.name = 'bfx'
b.why = {
    bday: 'b'
}
console.log(b)
console.log(newObj)      

 Object.create()方式建立

var newObj = {
    name: 'fx',
    why: {
        day: 1
    }
}
var b = Object.create(newObj)
console.log(b)
b.name = 'bfx'
b.why = {
    bday: 'b'
}
console.log(b)
console.log(newObj)      

例:

// 建立一個以另一個空對象為原型,且擁有一個屬性p的對象
o = Object.create({}, { p: { value: 42 } })

// 省略了的屬性特性預設為false,是以屬性p是不可寫,不可枚舉,不可配置的:
o.p = 24 
console.log(o.p) // 42

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

delete o.p // false
delete o.q // true

//建立一個可寫的,可枚舉的,可配置的屬性p
o2 = Object.create({}, {
  p: {
    value: 42, 
    writable: true,
    enumerable: true,
    configurable: true 
  } 
});      

用 Object.create實作類式繼承

// Shape - 父類(superclass)
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 - 子類(subclass)
function Rectangle() {
  Shape.call(this); // call super constructor.
}

// 子類續承父類
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.'      
function MyClass() {
     SuperClass.call(this);
     OtherSuperClass.call(this);
}

// 繼承一個類
MyClass.prototype = Object.create(SuperClass.prototype);
// 混合其它
Object.assign(MyClass.prototype, OtherSuperClass.prototype);
// 重新指定constructor
MyClass.prototype.constructor = MyClass;

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

// 建立一個原型為null的空對象
o = Object.create(null);


o = {};
// 以字面量方式建立的空對象就相當于:
o = Object.create(Object.prototype);


o = Object.create(Object.prototype, {
  // foo會成為所建立對象的資料屬性
  foo: { 
    writable:true,
    configurable:true,
    value: "hello" 
  },
  // bar會成為所建立對象的通路器屬性
  bar: {
    configurable: false,
    get: function() { return 10 },
    set: function(value) {
      console.log("Setting `o.bar` to", value);
    }
  }
});


function Constructor(){}
o = new Constructor();
// 上面的一句就相當于:
o = Object.create(Constructor.prototype);
// 當然,如果在Constructor函數中有一些初始化代碼,Object.create不能執行那些代碼      

繼續閱讀