javascript - js关于对象中this的问题?
本文介绍了javascript - js关于对象中this的问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
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
很不解?求高手相助...
解决方案
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判断。
这篇关于javascript - js关于对象中this的问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文