文章目录
**bind的作用是什么?****bind怎么用?****注意bind与call,apply的区别****bind可以传递两个参数****bind的第二个参数可以分两次传入****返回的新函数也能作为构造函数**解析bind的源码总结
bind的作用是什么?
简单来说:用来改变函数中的this指向
bind怎么用?
正常函数执行
function text (x
,y
,z
){
console
.log(this,x
,y
,z
)}
text(1,2,3)
使用bind时函数执行
function text(x
,y
,z
){
console
.log(this,x
,y
,z
)
}
var obj
= {};
var mytext
= text
.bind(obj
,1,2);
mytext(3);
注意bind与call,apply的区别
mytext = function test () {
console
.log(obj
,x
,y
,z
)
}
bind可以传递两个参数
第一个参数为需改变的this指向
第二个参数为函数执行时对应的实参列表
bind的第二个参数可以分两次传入
var mytext
= text
.bind(obj
,1,2);
mytext(3);
返回的新函数也能作为构造函数
function text(x
,y
,z
){
console
.log(this,x
,y
,z
)
}
var obj
= {};
var mytext
= text
.bind(obj
,1,2);
new mytext(3)
注意:此时bind改变
this无效 ,
this为text
{}
解析bind的源码
function text(x
,y
,z
){
console
.log(this,x
,y
,z
)
}
var obj
= {};
Function
.proptype
.bind = function(target
){
var self
= this;
var arg
= Array
.prototype
.slice
.call(arguments
,1);
var temp = function(){};
var fn = function (){
var _arg
= Array
.prototype
.slice
.call(arguments
,0);
self
.call(this instanceof temp? this :target
|| window
,arg
.concat(_arg
));
}
temp
.prototype
= self
.prototype
;
fn
.prototype
= new temp()
return fn
}
var mytext
= text
.bind(obj
,1,2);
mytext(3);
new mytext(3)
总结
1.使用bind后原函数会返回一个改变this指向的函数
2.实际上使用的功能还是原函数的
3.bind可以传递两个参数,第二个参数可以分两步传入,两次传入的参数,会拼接在一起成为新函数执行时的实参
4.当返回的新函数,以new的方式作为构造函数使用时,则不会改变this的指