ES6 getter/method without curly braces

人盡茶涼 提交于 2019-12-07 07:41:42

问题


I have some classes which consist of many short getters/methods.

Example:

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

An arrow function with similar content may be written as follows:

() => this.pageConfig.jQuery || jQuery;

Which is a one-liner and thus consumes only 1/3 of vertical space.

But it is not a getter nor a method.

Is there a recommended way of writing getters/methods in the form of a one-liner? (if possible without curly braces and without the return keyword)

My getters and methods need not modify the object. They are just reading.


回答1:


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.




回答2:


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 )




回答3:


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.




回答4:


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


来源:https://stackoverflow.com/questions/42540301/es6-getter-method-without-curly-braces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!