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
很不解?求高手相助...

阅读 3.7k
5 个回答

this的作用域问题。个人有个小技巧是
1.判断离最近的父function,这里且叫fatherFunc
2.fatherFunc是构造函数或prototype函数,或者bind了对象,则this指向对象;否则this指向fatherFunc的调用环境:

  • 父函数正常调用fatherFunc()时,this指向windowglobal;

  • 指定执行环境时fatherFunc.apply(obj,args) fatherFunc.call(obj,args)this指向对象obj;

  • 作为DOM事件处理函数:element.addEventListener(eventType,fatherFunc);element.onEventType = fatherFunc;this指向DOM元素。

具体判断过程
以下示例:
图片描述

三种颜色分别代表不同的this判断。

同意一楼。
这个方法属于谁,this就指向谁

既然bind(this)了,那this就是this,也就是a

还有这命名作者你出来我保证打不死你

最后一个问题的话吧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();
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题