javascript - js关于对象中this的问题?
黄舟
黄舟 2017-04-11 10:40:55
0
5
290
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();
            최신 다운로드
            더>
            웹 효과
            웹사이트 소스 코드
            웹사이트 자료
            프론트엔드 템플릿
            회사 소개 부인 성명 Sitemap
            PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!