Object.create()方法的使用详解

Object.create(prototype, descriptors)
创建一个具有指定原型且可选择性地包含指定属性的对象。

 
 

prototype

必需。  要用作原型的对象。  可以为 null  

descriptors

可选。  包含一个或多个属性描述符的 JavaScript 对象。  

“数据属性”是可获取且可设置值的属性。  数据属性描述符包含 value 特性,以及 writableenumerable 和 configurable 特性。  如果未指定最后三个特性,则它们默认为 false  只要检索或设置该值,“访问器属性”就会调用用户提供的函数。  访问器属性描述符包含 set 特性和/或 get 特性。  有关详细信息,请参阅 Object.defineProperty 函数 (JavaScript)  

一个具有指定的内部原型且包含指定的属性(如果有)的新对象。

如果满足下列任一条件,则将引发 TypeError 异常:

  • prototype 参数不是对象且不为 null

  • descriptors 参数中的描述符具有 value 或 writable 特性,并具有 get 或 set 特性。

  • descriptors 参数中的描述符具有不为函数的 get 或 set 特性。

ExceptionCondition

若要停止原型链,可以使用采用了 null prototype 参数的函数。  所创建的对象将没有原型。  

示例

下面的示例创建使用 null 原型的对象并添加两个可枚举的属性。

var newObj = Object.create(null, {
            size: {
                value: "large",
                enumerable: true
            },
            shape: {
                value: "round",
                enumerable: true
            }
        });

document.write(newObj.size + "<br/>");
document.write(newObj.shape + "<br/>");
document.write(Object.getPrototypeOf(newObj));

// Output:
// large
// round
// null

示例

下面的示例创建一个具有与 Object 对象相同的内部原型的对象。  您会发现,该对象具有与使用对象文本创建的对象相同的原型。  Object.getPrototypeOf 函数可获取原始对象的原型。  若要获取对象的属性描述符,可以使用Object.getOwnPropertyDescriptor 函数 (JavaScript)  

var firstLine = { x: undefined, y: undefined };

var secondLine = Object.create(Object.prototype, {
        x: {
                value: undefined, 
                writable: true, 
                configurable: true, 
                enumerable: true
            },
            y: {
                value: undefined, 
                writable: true, 
                configurable: true, 
                enumerable: true
            }
});

document.write("first line prototype = " + Object.getPrototypeOf(firstLine));
document.write("<br/>");
document.write("second line prototype = " + Object.getPrototypeOf(secondLine));

// Output:
// first line prototype = [object Object]
// second line prototype = [object Object]

示例

下面的示例创建一个具有与 Shape 对象相同的内部原型的对象。

// Create the shape object.
var Shape = { twoDimensional: true, color: undefined, hasLineSegments: undefined };

var Square = Object.create(Object.getPrototypeOf(Shape)); 

要求

在以下文档模式中受支持:Internet Explorer 9 标准模式、Internet Explorer 10 标准模式和 Internet Explorer 11 标准模式。 此外,也在应用商店应用(Windows 8 和 Windows Phone 8.1)中受支持。 请参阅版本信息

在以下文档模式中不受支持:Quirks、Internet Explorer 6 标准模式、Internet Explorer 7 标准模式、Internet Explorer 8 标准模式


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值