ES6吸气剂/无花括号的方法 [英] ES6 getter/method without curly braces

查看:197
本文介绍了ES6吸气剂/无花括号的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



示例:

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

具有相似内容的箭头函数可能写成如下:

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

这是一个单行,因此只消耗1/3的垂直空间。



但它不是一个吸气者,也不是一种方法。



是否有推荐的写作方式吸气剂/方法以一线式的形式? (如果可能没有花括号,没有返回关键字)



我的getters和方法不需要修改对象。他们只是在阅读。

解决方案

不,没有什么比(可以跳过;

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

更多解释



您不能使用箭头函数(()=> this.pageConfig.jQuery || jQuery ),因为一个它不是一个getter函数和这个不是指对象的上下文,而是执行的上下文(可以是对象,但不一定要。



有 __ defineGetter __ 函数(一些文档),它允许您定义一个getter,它现在已被弃用,可能会比获取,但文档说,广泛使用,可能永远不会被删除。



幸运的是:我是疯狂的解决方案



  class Test {constructor(){this.pageConfig = {} this.pageConfig.jQuery =valuelet properties = {'jQuery':()=> this.pageConfig.jQuery || Default,'text':()=> this.pageConfig.text || default} for(let prop in properties)this .__ defineGetter __(prop,properties [prop])}} let t = new Testconsole.log(t.jQuery)console.log(t.text) 



快乐一个衬里(但老实说,只需使用 get ECMA 5)


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.

解决方案

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 )

这篇关于ES6吸气剂/无花括号的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆