实现JavaScript的Object.create方法

来源:互联网 发布:龙腾会计软件 编辑:程序博客网 时间:2024/05/16 13:46
// 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引擎中是可读可写的,在大部分新版浏览器得到了支持。