js如何获取正确的this?

有一个对象A:

function A(){
    this.Avar = 'hello';
}
A.prototype.breadcrumb = {
    push: function(){
        console.info(this.Avar);
    }
};
var a = new A();

我想添加一个breadcrumb对象,使用new A().breadcrumb.push,但是打印出来的this是{push: ...}对象,而不是A对象,我该怎么改造让他读的是A对象的上下文?

阅读 3k
4 个回答
function A() {
  this.Avar = 'hello'
}
A.prototype.breadcrumb = function() {
  const ctx = this
  return {
    push: function() {
      console.log(ctx.Avar)
    }
  }
}

new A().breadcrumb().push()

在不依赖实例的情况下是有方法的。
不过不确定你的需求是什么,如果仅仅是个链式操作可以这样。

"use strict";

function A(){
  this.Avar = 'hello';
}
A.prototype.breadcrumb = function() {
  return {
    push: () => {
      console.log(this.Avar);
    }
  };
};

new A().breadcrumb().push(); // 'hello'

在push上加一个let _this=this;

后面全用_this代替this就行了

function A(){

this.Avar = 'hello';
var self = this;
this.breadcrumb = {
    push:function(){
        console.log(self.Avar);
    }
};

}
var aa = new A();
aa.breadcrumb.push();

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题