JavaScript bind method does not work on getter property

前端 未结 2 1638
小鲜肉
小鲜肉 2021-01-17 10:53

Trying to do this:

var c = {
  x: \'other context\'
};

var o = {
  x: \'this context\',
  get otherContext () {
    alert(this.x);
  }.bind(c)
};

o.otherCon         


        
2条回答
  •  粉色の甜心
    2021-01-17 11:18

    The problem is that method syntax doesn't use function expressions. It's a defined syntactic structure.

    MethodDefinition[Yield] :

    PropertyName[?Yield] ( StrictFormalParameters ) { FunctionBody }

    GeneratorMethod[?Yield]

    get PropertyName[?Yield] ( ) { FunctionBody }

    set PropertyName[?Yield] ( PropertySetParameterList ) { FunctionBody }

    PropertySetParameterList :

    FormalParameter

    Since it isn't a function expression, you don't have access to the functions methods or properties.

    You can accomplish what you want with Object.defineProperty.

    var proxy = { ... };
    Object.defineProperty(proxy, 'left', {
      get: function() {
        return this.el.offsetLeft;
      }.bind(this)
    });
    

提交回复
热议问题