bind() 方法会返回一个新函数(称为绑定函数),绑定函数与原函数(使用bind()的函数)具备相同的函数体,可是绑定函数有新的this值和参数。浏览器
说白了,bind()就是建立一个有着新this和实参的函数。app
funName.bind(thisArg[, arg1[, arg2[, ...]]])
thisArgdom
绑定函数中this的指向。能够是null,undefined,{},或其余任意对象。能够是另一个函数。该参数不能被重写。函数
arg1, arg2, ...this
可选。传给绑定函数的参数。prototype
做为默认实参传递给绑定函数。code
假设参数是一个列表,如今有2种参数,一个是bind的实参参数,一个新的绑定函数中传递的实参参数。bind()的参数在绑定函数的参数的前面。对象
用法:可使绑定函数有初始的默认参数。作用域
例子:get
function funa(){ "use strict"; console.log(arguments[0]);//33 console.log(arguments[1]);//11 } var o = { x:1 } var funb = funa.bind(o,33); funb(11);//输出33 \n 11
支持bind()方法的浏览器有IE9+。
bind是ES5新增方法,不会执行对应的函数(call或apply会自动执行对应的函数),而是返回对绑定函数的引用。
构造函数可使用bind(),而后再次建立实例。
bind()提供的 this值被忽略,提供的那些参数仍然会被前置到构造函数调用的前面。
function Point(x, y) { this.x = x; this.y = y; } Point.prototype.toString = function () { return this.x + ',' + this.y; }; var p = new Point(1, 2); p.toString(); // '1,2' var YA = Point.bind(null, 0); var axis = new YA(5); axis.toString(); // '0,5' axis instanceof Point; // true axis instanceof YA; // true new Point(17, 42) instanceof YA; // true
例子:
window.color = "red"; var o = { color: "blue" }; function sayColor() { console.log(this.color); } var objectSayColor = sayColor.bind(o); objectSayColor(); //blue
目的:使对象的方法在不是这个对象使用时,this的指向依然是这个对象。
缘由:建立一个变量,指向为对象的方法,获得一个新函数。这个新函数中的this值已经再也不指向原对象了。
name = "hello"; var mo = { name:2010, getName:function(){ console.log(this.moyu); } }; mo.getName();//2010 var newMo = mo.getName;//在这种状况下,"this"指向全局做用域window。 newMo();//hello var nextMo = mo.getName.bind(mo); nextMo();//2010
bind()能够将undefined做为this指向,而后传入默认实参。
用法:
fun.bind(undefined,33);
function list(){ let res = Array.prototype.slice.call(arguments); console.log(res); } list(1,2,3);//[1,2,3] let newList = list.bind(null,3); newList();//[3] newList(1);//[2,1]
在默认状况下,使用setTimeout(function,time); 时,函数的this关键字会指向window。
在原型上的方法中,this是实例对象。使用setTimeout,必须显式的把实例对象绑定到它的函数中,不然this为window对象。
function LateBloomer() { this.petalCount = Math.ceil(Math.random() * 12) + 1; } LateBloomer.prototype.declare = function() { console.log('I am a beautiful flower with ' + this.petalCount + ' petals!'); }; LateBloomer.prototype.bloom = function() { console.log(this);//LateBloomer {patalCount:4}; setTimeout(this.declare.bind(this), 1000); //zxy456:2个this都是指向LateBloomer. //若是不加bind,setTimeout调用的函数的this为window。declare中的this变为window了。 }; var flower = new LateBloomer(); flower.bloom(); // 一秒钟后, 调用'declare'方法
zyx456思路:将bind()和函数的参数合并。而后运行apply便可。
if (!Function.prototype.bind) { Function.prototype.bind = function (o) { var self = this, arg = Array.prototype.slice.call(arguments, 1); var fbind = function () { var arr = [...arg, ...arguments]; // 如今将self做为o的方法来调用,传入这些实参 return self.apply(o, arr); }; fbind.prototype = this.prototype;//用于bind构造函数。 return fbind; }; }