JavaScript bind method does not work on getter property

前端 未结 2 1637
小鲜肉
小鲜肉 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:17

    For class proxies you might want to use something like this:

    class Main {
        constructor() {
            this._adapter = new Adapter();
            return this._createProxy();
        }
    
        _createProxy() {
            return new Proxy(this, {
                get(me, propertyName) {
                    if (typeof me._adapter[propertyName] === 'function') {
                        return me._adapter[propertyName].bind(me._adapter);
                    }
                    return (function () {
                        return me._adapter[propertyName];
                    }.bind(me._adapter))();
                }
            });
        }
    }
    
    class Adapter {
        constructor() {
            this._foo = true;
            this._yuk = 2;
        }
    
        get foo() {
            return this._foo;
        }
    
        baz() {
            return 4*this._yuk;
        }
    }
    

    This way both, the getter and the method will be wrapped within the right context:

    let main = new Main();
    console.log(main.foo);   // -> true
    console.log(main.baz()); // -> 8
    
    0 讨论(0)
  • 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)
    });
    
    0 讨论(0)
提交回复
热议问题