Question

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?
Was it helpful?

Solution

  • inline get/set are OK
  • they're not deprecated if favor of defineProperty (__defineGetter__ and __defineSetter__ are deprecated)
  • defineProperty gives to you more granularity and control over the property you're going to define: you can decide if the property is configurabile, writable and enumerable. You can't do that with get and set. In addition, with defineProperty you could not define necessary a getter or a setter, but just a value.
  • Use get and set when you do not need more granularity, it's a sugar syntax, and can be used in the object definition itself, where defineProperty has to be used once the instance is created. Use defineProperty when you need more granularity, or you do not need necessary to specify getter and setter but just a value.

Hope it helps.

Links to the specs about get and set

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top