美文网首页
Javascript的call和bind的区别

Javascript的call和bind的区别

作者: kallsaver | 来源:发表于2017-01-05 23:59 被阅读0次

var a={

name:"aaa"

}

var b={

name:"bbb"

}

var box=document.getElementsByClassName("box")[0];

box.onclick=function(){

console.log(this.name)

}.call(a) //call会马上执行  因为匿名函数的调用者不再是box了,onclick是box的属性

box.onclick=function(){

console.log(this.name)

}.bind(b) //bind要点击才执行

//事实上,函数执行时,this会作为一个隐形的参数传入函数体中

//bind函数的作用是指把传入的this参数改为bind的参数

var obj={

x:81

}

var foo={

getX:function(){

return this.x

}

}

console.log(foo.getX.bind(obj)()) //bind要加()才执行

console.log(foo.getX.call(obj))

console.log(foo.getX.apply(obj))

相关文章

网友评论

      本文标题:Javascript的call和bind的区别

      本文链接:https://www.haomeiwen.com/subject/lxrtbttx.html