在Object.create中使用属性描述符的正确方法是什么?

Bra*_*don 5 javascript prototype

我传递了一个对象作为方法中的第二个参数Object.create,但是我收到以下错误:

未捕获的TypeError:属性描述必须是对象:1

这是错误的代码:

var test = Object.create(null, {
    ex1: 1,
    ex2: 2,
    meth: function () {
        return 10;
    },
    meth1: function () {
        return this.meth();
    }
});
Run Code Online (Sandbox Code Playgroud)

Dmy*_*nko 14

Object.create(proto, props) 有两个参数:

  1. proto - 应该是新创建对象原型的对象.
  2. props (可选) - 一个对象,其属性指定要添加到新创建的对象的属性描述符,以及相应的属性名称.

此处props定义了对象的格式.

简而言之,每个属性描述符的可用选项如下:

{
    configurable: false, // or true
    enumerable: false, // or true
    value: undefined, // or any other value
    writable: false, // or true
    get: function () { /* return some value here */ },
    set: function (newValue) { /* set the new value of the property */ }
}
Run Code Online (Sandbox Code Playgroud)

代码的问题在于您定义的属性描述符不是对象.

以下是属性描述符的正确用法示例:

var test = Object.create(null, {
    ex1: {
        value: 1,
        writable: true
    },
    ex2: {
        value: 2,
        writable: true
    },
    meth: {
        get: function () {
            return 'high';
        }
    },
    meth1: {
        get: function () {
            return this.meth;
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 甲酸回报高 - 我哭了.XD (7认同)