ES6 getter/method without curly braces

放肆的年华 提交于 2019-12-05 12:14:38

For a one liner, just go with this:

get jQuery() {return this.pageConfig.jQuery || jQuery;}

Arrow functions are not for method definitions because they use the lexical this, whereas a method wants the object this. Remember that while arrow functions are a nice shorthand, they also affect the value of this in a way that is not usually compatible with method definitions.

No, there is nothing shorter than ( you can skip the ; )

get jQuery() { return this.pageConfig.jQuery || jQuery }

A bit more explanation

You can't use the arrow function ( () => this.pageConfig.jQuery || jQuery ), because for one it is not a getter function and this doesn't refer to the context of the object but the context of execution (which could be the object but doesn't have to.

There is/was the __defineGetter__ function ( some documentation ) which allows you to define a getter. It is now deprecated and probably would be even more complex than the get. But as the docs say, it's used widely and will probably never get removed.

Luckily for you: I'm all for crazy solutions

class Test {
  
  constructor() {
    this.pageConfig = {}
    this.pageConfig.jQuery = "value"
    
    let properties = {
      'jQuery': () => this.pageConfig.jQuery || "Default",
      'text': () => this.pageConfig.text || "Default"
    }
    for(let prop in properties) this.__defineGetter__(prop, properties[prop])
    
  }
  
}

let t = new Test
console.log(t.jQuery)
console.log(t.text)

Happy one lining ( but honestly just use the get from ECMA 5 )

Nice one-liner solution:

readonly jQuery = this.pageConfig.jQuery || jQuery

It is short, behaves like you would expect it from the getter, and needs no curly braces.

I was thinking of building a babel library to handle this I think something like this would look fancy

const weekDays = [
            {
                day: 'Sunday',
                get input() {
                    return TimeRange(this.day)
                }
                // something like this
                // get input() => TimeRange(this.day)
            }
]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!