最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - What's the proper way of using property descriptors in Object.create? - Stack Overflow

programmeradmin3浏览0评论

I passed an object as the second parameter in the Object.create method, but I'm getting the following error:

Uncaught TypeError: Property description must be an object: 1

Here's the faulty code:

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

I passed an object as the second parameter in the Object.create method, but I'm getting the following error:

Uncaught TypeError: Property description must be an object: 1

Here's the faulty code:

var test = Object.create(null, {
    ex1: 1,
    ex2: 2,
    meth: function () {
        return 10;
    },
    meth1: function () {
        return this.meth();
    }
});
Share Improve this question edited Jun 7, 2016 at 8:19 Dmytro Shevchenko 34.6k6 gold badges55 silver badges68 bronze badges asked Jun 7, 2016 at 7:09 BrandonBrandon 1,1951 gold badge10 silver badges16 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 17

Object.create(proto, props) has two arguments:

  1. proto — the object which should be the prototype of the newly-created object.
  2. props (optional) — an object whose properties specify property descriptors to be added to the newly-created object, with the corresponding property names.

The format for the props object is defined here.

In short, the available options for each property descriptor are these:

{
    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 */ }
}

The problem with your code is that the property descriptors you've defined are not objects.

Here's an example of a proper usage of property descriptors:

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;
        }
    }
});

Did you try this syntax :

    var test = {
      ex1: 1,
      ex2: 2,
      meth: function() {
        return 10;
      },
      meth1: function() {
        return this.meth()
      }
    };

    console.log("test.ex1 :"+test.ex1);
    console.log("test.meth() :"+test.meth());
    console.log("test.meth1() :" + test.meth1() );

发布评论

评论列表(0)

  1. 暂无评论