1

There seems to be an overlap in functionality between inline, object literal 'get function()' style and Object.defineProperty.

MDN docs for get https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/get don't mention that inline 'get' functions are deprecated.

    var john = {
        firstName: 'John',
        lastName:  'Smith',
        age:        21,
        gender:     'Male'

        // () → String
        // Returns the full name of object.
        get name() {
            return this.firstName + ' ' + this.lastName
        },

        // (new_name:String) → undefined
        // Sets the name components of the object,
        // from a full name.
        set name(new_name) {
            var names = new_name.trim().split(/\s+/)
            this.firstName = names['0'] || ''
            this.lastName  = names['1'] || ''
        },
    }

This article from Mozilla's Jeff Walden in (what seems to be) 2010 stated:

"We’ve removed support for a handful of obsolete getter/setter syntaxes in SpiderMonkey and Mozilla. This does not include { get property() { return "value"; }, set property(v) { } }, which is widely used and which is part of the latest standard."

So:

  • Is inline get/set OK?
  • Is inline get/set deprecated in favor of defineProperty?
  • When should I use each?
4

1 回答 1

7
  • 内联获取/设置都可以
  • defineProperty如果支持(__defineGetter__并且不推荐使用) ,它们不会__defineSetter__被弃用
  • defineProperty为您提供对要定义的属性的更多粒度和控制:您可以决定该属性是否为configurabile,writableenumerable. 你不能用getand做到这一点set。此外,defineProperty您无法定义必要的 getter 或 setter,而只能定义一个值。
  • 使用getandset当您不需要更多粒度时,它是一种糖语法,可以在对象定义本身中defineProperty使用,一旦创建实例就必须在其中使用。当您需要更多粒度时使用defineProperty,或者您不需要指定 getter 和 setter 而只是一个值。

希望能帮助到你。

get链接到关于和的规格set

ES5: http: //www.ecma-international.org/ecma-262/5.1/#sec-11.1.5

ES6(草案): http: //people.mozilla.org/~jorendorff/es6-draft.html#sec-method-definitions-static-semantics-propname

于 2013-10-24T11:18:50.637 回答