javascript中的call()和bind()

来源:互联网 发布:网页淘宝分享到微信 编辑:程序博客网 时间:2024/06/09 15:24
var name = 'global';var obj = {  name : 'obj',  dose : function(){    this.name = 'dose';    return function(){      return this.name;    }  }}alert(obj.dose().call(this))

在window的执行环境下,call的this指的是window,跟obj.dose()无关.

function() {    return this.name;}

中的this指向的是window(其实本来匿名函数的this就是指向window的,感觉这里多次一举了)

var name = 'global';var obj = {  name : 'obj',  dose : function(){    this.name = 'dose';    return function(){      return this.name;    }.bind(this)  }}alert(obj.dose().call(this))
这里function中用bind(this)绑定了this为obj.所以即使call把this传进来,this还是obj.所以输出还是obj

0 0
原创粉丝点击