首先:javascript
var alertWrite = document.write; alertWrite('who am I?');
这两行代码的运行结果是什么呢?不要急着回答,看完下面的内容再回答。java
看下面的例子:数组
var obj = { getThis: function() { console.log(this); } };
obj.getThis(); var getThisCopy = obj.getThis; getThisCopy();
运行结果以下:浏览器
经过上述例子咱们会发现,虽然是 getThisCopy 是复制了 obj 的 getThis 方法,可是他们所属的对象却不同。在对象里面,全部的 this 都指向对象自己,而在全局做用域定义的变量的 this 指向 Window。app
因此,下面这段代码的运行结果,能猜的出来结果吗?函数
1 var obj = { 2 num: 100, 3 numFun: function() { 4 console.log(this.num); 5 } 6 }; 7 var numFunCopy = obj.numFun; 8 numFunCopy();
bind 的存在就是 为了解决 this 不可以指向原来的问题。this
因此,试试这段代码:spa
1 var alertWrite = document.write; 2 alertWrite.bind(document)('hello');
4 var obj = { 5 getThis: function(){ 6 console.log(this); 7 } 8 } 9 var getThisCopy = obj.getThis; 10 getThisCopy.bind(obj)(); 11 12
13 var obj = { 14 num: 100, 15 numFun: function(){ 16 console.log(this.num); 17 } 18 } 19 var numFunCopy = obj.numFun; 20 numFunCopy.bind(obj)();
总结bind使用方法:prototype
fun.bind(thisArgument, argument1, argument2, ...)code
thisArgument:在 fun 函数运行时指定的 this 值,若是绑定函数时使用 new 运算符构造的,则该值将被忽略。
argument1, argument2, ...:指定的参数列表。
返回值:具备指定 this 值和初始参数的给定函数的副本
使用1:建立绑定函数,使函数不管怎么样调用,都有相同的 this 值
1 this.x = 9; 2 var module = { 3 x: 81, 4 getX: function() { return this.x; } 5 }; 6 7 module.getX(); // 返回 81 8 9 var retrieveX = module.getX; 10 retrieveX(); // 返回 9, 在这种状况下,"this"指向全局做用域 11 12 // 建立一个新函数,将"this"绑定到module对象 13 // 新手可能会被全局的x变量和module里的属性x所迷惑 14 var boundGetX = retrieveX.bind(module); 15 boundGetX(); // 返回 81
使用2:偏函数,使一个函数拥有预设值。
可是 bind 是 ES5 的内容,有必定的兼容性问题。
解决bind兼容性方案(1)
1 //解决IE10如下不支持Function.bind 2 if (!Function.prototype.bind) { 3 Function.prototype.bind = function(oThis) { 4 if (typeof this !== "function") { 5 throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable"); 6 } 7 var aArgs = Array.prototype.slice.call(arguments, 1), 8 fToBind = this, 9 fNOP = function() {}, 10 fBound = function() { 11 return fToBind.apply(this instanceof fNOP && oThis ? this : oThis, 12 aArgs.concat(Array.prototype.slice.call(arguments))); 13 }; 14 fNOP.prototype = this.prototype; 15 fBound.prototype = new fNOP(); 16 return fBound; 17 }; 18 }
解决bind兼容性方案(2)
1 if (!function() {}.bind) { 2 Function.prototype.bind = function(context) { 3 var self = this 4 , args = Array.prototype.slice.call(arguments); 5 return function() { 6 return self.apply(context, args.slice(1)); 7 } 8 }; 9 }
语法:fun.call(thisArgument, argument1, argument2, ...)
thisArgument:在 fun 函数运行时指定的 this 值。在非严格模式下,该函数 this 指定为 null 和 undefined ,则 this 值会自动只想全局对象,同时只为原始值的 this 会指向该原始值的自动包装对象。
argument*:指定的参数列表。
返回值:调用该方法的返回值,若是没有,则返回undefined。
使用1:使用 call 方法来实现继承
使用2:使用 call 调用匿名函数,方法为for循环传入不一样的对象
使用3:指定上下文 this
语法:fun.apply(thisArg [, argsArray])
thisArg:可选,在非严格模式下,若是 this 值设置为 null/undefined,则 this 指向去全局对象(浏览器中就是 window 对象),同时为原始值(数字,字符串,布尔值)的 this 会指向该原始的包装对象。
argsArray:可选。数组或者类数组对象(从ES5开始能够使用类数组对象)。
返回值:调用有指定this值和参数的函数的结果。
使用:其使用跟 call() 很是类似,只是提供参数的方式不一样。