Javascript Bind研究详情

102 阅读1分钟

thisObj={ ... };

myFunc (oldParam){ this.something };

myFunc.bind(thisObj,newParam)

  1. bind仅限于函数
  2. bind的目的很简单,就是生成一个崭新的函数,然后把函数里面的this指定到bind的第一个参数里面 注意:
  3. bind返回的是一个崭新的函数,并没有被执行!如果执行需要调用,或者直接.call
  4. 关键是:除了thisOjb,如果传入了新的参数newParam会自动传入进去,再调用的时候传入的参数不受影响。
  5. 即第一个参数是函数的context参数,后面的参数是初始化参数。

看文档:

再看优雅的React应用实例:

当然上面的方法也可以通过closure实现:

callbackFnFactory: function(key) {
  // key is "result.id"
 return this.props.callbackFn(key);
},

render: function() {
  var results = this.props.results;
  return (
    <div>
      {results.map(function(result) {
        return (
          <ChildComponent type="text" key={result.id}
            changeCallback={this.callbackFnFactory(result.id)} />
        );
      }, this)}
    </div>
  );
}

Bind的方法应该更明了,更胜一筹!

参考: www.codementor.io/niladrisekh…

developer.mozilla.org/en-US/docs/…

stackoverflow.com/questions/2…