鍍金池/ 問答/HTML/ js如何獲取正確的this?

js如何獲取正確的this?

有一個(gè)對象A:

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

我想添加一個(gè)breadcrumb對象,使用new A().breadcrumb.push,但是打印出來的this是{push: ...}對象,而不是A對象,我該怎么改造讓他讀的是A對象的上下文?

回答
編輯回答
不舍棄

function A(){

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

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

2017年12月31日 11:08
編輯回答
來守候

在push上加一個(gè)let _this=this;

后面全用_this代替this就行了

2018年4月21日 04:35
編輯回答
凝雅

在不依賴實(shí)例的情況下是有方法的。
不過不確定你的需求是什么,如果僅僅是個(gè)鏈?zhǔn)讲僮骺梢赃@樣。

"use strict";

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

new A().breadcrumb().push(); // 'hello'
2018年5月5日 23:35
編輯回答
尕筱澄
function A() {
  this.Avar = 'hello'
}
A.prototype.breadcrumb = function() {
  const ctx = this
  return {
    push: function() {
      console.log(ctx.Avar)
    }
  }
}

new A().breadcrumb().push()
2018年9月3日 18:44