實現JavaScript的Object.create方法

// prototype - 將被創建對象的原型
// properties (可選) - 將被創建對象需要添加的屬性
//
// throws TypeError 如果 'prototype' 參數不是一個對象,也不是null
//
// returns 新創建的對象

Object.create = function foo(prototype, properties) {
    if(typeof prototype !== "object"){
        throw TypeError();
    }
    var obj = {};
	//設置原型
    obj.__proto__ = prototype;
    if(typeof properties !== "undefined"){
        Object.defineProperties(obj,properties);
    }
    return obj;
};

注:__proto__屬性在V8的JavaScript引擎中是可讀可寫的,在大部分新版瀏覽器得到了支持。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章