javascript - js关于对象中this的问题?
黄舟
黄舟 2017-04-11 10:40:55
[JavaScript讨论组]
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
很不解?求高手相助...

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

全部回复(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 都是 a,自己仔细理一理就好了,
你该的错误代码里, this 是 promise 对象。
http://zonxin.github.io/post/2015/11/javascript-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();
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号