Binding different this scope to ES6 => function operator

后端 未结 2 1134
走了就别回头了
走了就别回头了 2021-02-09 13:04

After experimenting with inheriting contexts with the => feature that ES6 gives us I noticed that the this context can never be changed. Example:

var otherConte         


        
2条回答
  •  眼角桃花
    2021-02-09 13:15

    It is effectively just new syntax for bind, so this doesn't introduce anything new in the way of gotchas.

    var otherContext = {
      a: 2
    };
    function foo() {
      this.a = 1;
      this.bar = function () { return this.a }.bind(this);
    }
    
    var instance = new foo;
    log(instance.bar()); // returns 1
    log(instance.bar.bind(otherContext)()); // returns 1
    
    function log(value) { 
      document.body.appendChild(
        document.createTextNode(value)
      );
    }

    Therefore, if we receive a function from an external call or just have a function in a variable, how can we be sure if we are going to be able to bind a different this to it or if it will just inherit it from somewhere?

    Because either:

    1. You'll have written that function in the first place or
    2. You'll have written a specification for how to call your function so that people know to pass in a function which makes use of this from a context you choose.

提交回复
热议问题