Javascript 获得;这";JS中的上下文;“类”;方法函数

Javascript 获得;这";JS中的上下文;“类”;方法函数,javascript,jquery,Javascript,Jquery,我试图在JS中创建一个“类”,其简化结构如下: 当您单击文档时,它会在控制台中显示此消息的内容。但是,它现在显示为未定义。我认为问题在于this.message无法获取原始this上下文,因为它是另一个函数中的包装器(setTimeout)。任何帮助都将不胜感激 以下是对我有效的方法,您可以通过引用self获得您的this.message,这是您需要的正确上下文 function Alert() { this.message = "Test alert"; this.documen

我试图在JS中创建一个“类”,其简化结构如下:


当您单击
文档
时,它会在控制台中显示
此消息的内容。但是,它现在显示为
未定义
。我认为问题在于
this.message
无法获取原始
this
上下文,因为它是另一个函数中的包装器(
setTimeout
)。任何帮助都将不胜感激

以下是对我有效的方法,您可以通过引用
self
获得您的
this.message
,这是您需要的正确上下文

function Alert() {  
  this.message = "Test alert";
  this.document = $(document);
  this.document.on('click', function() {
  this.show();
}.bind(this));
};
Alert.prototype.show = function() {
  var self = this;
  setTimeout(function() {
    console.log(self.message);
  }, 50);
};
var alert = new Alert();

您可以使用箭头函数来保存上下文

function Alert() {
  this.message = "Test alert";
  this.document = $(document);

  this.document.on('click', () => {
     this.show();
  });

};

Alert.prototype.show = function () {
  setTimeout(() => {
    console.log(this.message);
  }, 50);
};

var alert = new Alert();

阅读更多信息:。

可能重复严重,您的代码中已经有了
bind
,谢谢!这两种方法都很有效,只是觉得这一种更简单一些。
function Alert() {
  this.message = "Test alert";
  this.document = $(document);

  this.document.on('click', () => {
     this.show();
  });

};

Alert.prototype.show = function () {
  setTimeout(() => {
    console.log(this.message);
  }, 50);
};

var alert = new Alert();