function A() {}
A.prototype.b = function(){
var dtd = $.Deferred();
var cha = function() {
dtd.resolve();
}
setTimeout(cha,5000);
return dtd;
}
A.prototype.wan = function() {
console.log("结束");
}
A.prototype.action = function(){
var that = this;
var b = function() {
return this.b.apply(this, arguments)
}.bind(this);
b().then(function(){
that.wan();
});
}
var a = new A(); a.action();
这是我copy的一段代码,其中
var that = this;
var b = function() {
return this.b.apply(this, arguments)
}.bind(this);
这一段的this指向真是考验脑细胞(全局? or A函数? or b方法?),原型方法b中的var that = this,这个this应该指向的A函数对象,this.b.apply(this...然后把this的b又指向this还不够 ,最后bind(this)又指向一次,彻底晕菜+_+?求高手指点迷津
如果我把最后一段
b().then(function(){
that.wan();
});
改成
b().then(function(){
this.wan();
}.bind(A));
维森么 会报错?显示一个this.wan is not a function
很不解?求高手相助...
既然bind(this)了,那this就是this,也就是a
还有这命名作者你出来我保证打不死你
this
的作用域问题。个人有个小技巧是
1.判断离最近的父function
,这里且叫fatherFunc
2.fatherFunc
是构造函数或prototype
函数,或者bind
了对象,则this
指向对象;否则this
指向fatherFunc
的调用环境:
父函数正常调用
fatherFunc()
时,this
指向window
或global
;指定执行环境时
fatherFunc.apply(obj,args)
或fatherFunc.call(obj,args)
,this
指向对象obj;作为DOM事件处理函数:
element.addEventListener(eventType,fatherFunc);
或element.onEventType = fatherFunc;
,this
指向DOM元素。
以下示例:
三种颜色分别代表不同的this判断。
最后一个问题的话吧A改成a就行了, 很简单的理由: a是一个实例化对象, 而A是一个构造函数...
b().then(function(){
this.wan();
}.bind(a));
关于前面的this
function A() {}
A.prototype.b = function(){
var dtd = $.Deferred();
var cha = function() {
dtd.resolve();
}
setTimeout(cha,500);
return dtd;
}
A.prototype.wan = function() {
console.log("结束");
}
A.prototype.action = function(){
var that = this; //函数调用中that保证this的正常作用域
var b = function() {
console.log(this);
return this.b.apply(this, arguments) //由下面的bind得知这里的this会指向A而不是b, 原因应该是函数调用中this不会指向该函数名(设计缺陷)
}.bind(this); //这边的this指向A对象
b().then(function(){
that.wan();
});
}
var a = new A();
a.action();
第一段,没有错的的代码里,所有的 this 都是 a
,自己仔细理一理就好了,
你该的错误代码里, this
是 promise 对象。
http://zonxin.github.io/post/2015/11/javascript-this
同意一楼。
这个方法属于谁,this就指向谁