ES6 getter/setter with arrow function

后端 未结 2 684
滥情空心
滥情空心 2020-12-28 11:20

I\'m using babel6 and for my pet project I\'m creating a wrapper for XMLHttpRequest, for the methods I can use:

open = (method, url, something) => {
  ret         


        
2条回答
  •  伪装坚强ぢ
    2020-12-28 11:50

    The accepted answer is great. It's the best if you're willing to use normal function syntax instead of compact "arrow function syntax".

    But maybe you really like arrow functions; maybe you use the arrow function for another reason which a normal function syntax cannot replace; you may need a different solution.

    For example, I notice OP uses this, you may want to bind this lexically; aka "non-binding of this"), and arrow functions are good for that lexical binding.

    You can still use an arrow function with a getter via the Object.defineProperty technique.

    {
      ...
      Object.defineProperty(your_obj, 'status', { 
         get : () => this.xhr.status 
      });
      ...
    }
    

    See mentions of object initialization technique (aka get NAME() {...}) vs the defineProperty technique (aka get : ()=>{}). There is at least one significant difference, using defineProperty requires the variables already exists:

    Defining a getter on existing objects

    i.e. with Object.defineProperty you must ensure that your_obj (in my example) exists and is saved into a variable (whereas with a object-initialization you could return an object-literal in your object initialization: {..., get(){ }, ... }). More info on Object.defineProperty specifically, here

    Object.defineProperty(...) seems to have comparable browser support to the get NAME(){...} syntax; modern browsers, IE 9.

提交回复
热议问题