Javascript继承和失去“this”的上下文 [英] Javascript Inheritance and losing the context of 'this'

查看:128
本文介绍了Javascript继承和失去“this”的上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用John Resig的简单JavaScript继承,并且遇到了一个问题,我失去了这个指的是什么。使用此代码:

I am using John Resig's Simple JavaScript Inheritance and have run into an issue where I am losing what 'this' refers to. Using this code:

var Runner = Class.extend({ 
 init: function() {
  this.update();
  if(!this.interval) {
   this.interval = setInterval(this.update, this.period * 1000);
  }
 },
 stop: function() {
  clearInterval(this.interval);
 },
 update: function() {
  this.success()
 },
 success: function(){
 }
});

var SubRunner = Runner.extend({
 update: function() {
  this._super();
 },
 success: function(){
  alert('sub runner success');
 }
});

运行 p = new SubRunner()正如我预期的,并且第一次提醒子经理成功。在第一次运行之后,然后尝试在错误的this(窗口)上运行成功函数。

Running p = new SubRunner() works as I would expect and alerts sub runner success the first time. After the first run through it then tries to run the success function on the wrong 'this' (window).

我知道Prototype给你一个绑定函数,所以你可以传递上下文到函数,但我没有运气做类似这里。

I know Prototype gives you a bind function so that you can pass the context to the function but I haven't had any luck in doing something similar here. Does anyone have a starting point to figuring this out?

推荐答案

问题是当你传递this.update到setInterval函数。在Javascript中,this取决于你使用点符号调用函数,并且函数不会记住它们来自哪里,如果你将它们作为回调传递或将它们存储在一个变量中。

The problem is when you pass this.update to the setInterval function. In Javascript, the "this" depends on wether you call the function using dot notation, and functions will not remember where they came from if you pass them as callbacks or store them in a variable.

您可以添加包装函数

var that = this;
setTimeout(function(){ that.update() }, this.perios*1000)

或者您可以使用绑定方法(如果它在浏览器中可用)(或者您可以在Prototype中使用类似的函数)。

or you can use the bind method if its available in your browser (or you can use the similar function in Prototype).

setTimeout(this.update.bind(this), this.period*1000)

这篇关于Javascript继承和失去“this”的上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆