开发者

variable.Property = "test" vs Object.defineProperty(variable,"Property")

If I want to give a variable a a property P (non-accessor property) and I do not care if it's configurable/enumerable/writable.

I can be 100% sure it is in fact more beneficial (in all ways you can think of) to simply do a开发者_Python百科

a.P=value     // or
a["P"]=value

instead of using

Object.defineProperty

So basically as a rule, we should not touch that Object.defineProperty unless we need to create accessors and/or we want to control the configurable/writable/enumerable status of the properties?


I wouldn't say it's "more beneficial", but these are identical in functionality:

a.p = value;

Object.defineProperty(a, 'p', {
    enumerable   : true,
    writable     : true,
    configurable : true,
    value        : value
});

Obviously the latter is much more verbose, also much slower (roughly 1,000x slower in Chrome) if you're defining many properties:

http://jsperf.com/setting-object-properties

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜