实现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引擎中是可读可写的,在大部分新版浏览器得到了支持。

猜你喜欢

转载自blog.csdn.net/esir82/article/details/78068935