js手札--bind

bind {
处理题目:callback() { this ? //谁在用 }
}

function callback() {
   console.log(this);
}

function foo(cb) {
  cb();
}

foo(callback);  // 输出的this是谁的呢?  =>  全局window的
foo(callback.bind(callback));  // 输出的this是谁的呢?  =>  callback的
foo(callback.bind(foo));  // 输出的this是谁的呢?  =>  foo的

来看个详细的题目(背面就举了个例子,没兴趣的能够到此为止了。篇幅比较短,包涵) =>

一、题目再现

// 把['x','y',1,2]拷贝到lost.arr中

var lost = {
    arr : [],
    pushArray: function(s) {
        this.arr.push(s);
    }
};

// error 不认识arr
// 由于作用域题目。如今挪用pushArray的对象是window,而window是没有arr的
['x','y',1,2].forEach(lost.pushArray);

《js手札--bind》

二、证实题目

那末怎样就可以证实是window对象挪用了lost.pushArray呢。

window.arr = [];
['x','y',1,2].forEach(lost.pushArray);
console.log(window.arr);

《js手札--bind》

三、处理方法

I.运用匿名函数

实在看看上面的丧失缘由以后,就知道了实在pushArray的运用权被window对象夺去了,而我们需要让lost夺回pushArray的运用权。

// 在中心代码前,加一层壳(匿名函数),让window运用这个匿名函数,就处理了
['x','y',1,2].forEach(function(s) { // 匿名函数
    // 中心代码
    lost.pushArray(s);
});

II.运用bind

运用bind就比较文雅了。

['x','y',1,2].forEach(lost.pushArray.bind(lost));

连系第一种处理方法,斗胆勇敢的猜想,bind的伪完成能够是,相当于返回一个匿名函数。

function bind(me) {
   var fn = this;
   return function() {
       fn.apply(me, arguments);
   }
}

考证一下,哈哈,效果和bind一样哟。
《js手札--bind》

    原文作者:foolishq
    原文地址: https://segmentfault.com/a/1190000005133592
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞