'this'在JavaScript类方法中未定义 [英] 'this' is undefined in JavaScript class methods

查看:119
本文介绍了'this'在JavaScript类方法中未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JavaScript的新手。我已经完成的所有新功能都是对现有代码进行了调整,并编写了一小段jQuery。

I'm new to JavaScript. New as far as all I've really done with it is tweaked existing code and wrote small bits of jQuery.

现在我正在尝试编写一个类属性和方法,但我遇到了这些方法的问题。我的代码:

Now I'm attempting to write a "class" with attributes and methods, but I'm having trouble with the methods. My code:

function Request(destination, stay_open) {
    this.state = "ready";
    this.xhr = null;
    this.destination = destination;
    this.stay_open = stay_open;

    this.open = function(data) {
        this.xhr = $.ajax({
            url: destination,
            success: this.handle_response,
            error: this.handle_failure,
            timeout: 100000000,
            data: data,
            dataType: 'json',
        });
    };

    /* snip... */

}

Request.prototype.start = function() {
    if( this.stay_open == true ) {
        this.open({msg: 'listen'});
    } else {

    }
};
//all console.log's omitted

问题是, Request.prototype.start 未定义,因此if语句的计算结果为false。我在这做错了什么?

The problem is, in Request.prototype.start, this is undefined and thus the if statement evaluates to false. What am I doing wrong here?

推荐答案

你是如何调用启动函数的?

How are you calling the start function?

这应该是工作(是关键)

This should work (new is the key)

var o = new Request(destination, stay_open);
o.start();

如果你直接称它为 Request.prototype.start()将引用全局上下文(浏览器中的窗口)。

If you directly call it like Request.prototype.start(), this will refer to the global context (window in browsers).

此外,如果未定义此,则会导致错误。 if表达式的计算结果为false。

Also, if this is undefined, it results in an error. The if expression does not evaluate to false.

更新对象不是基于声明设置,但通过调用。这意味着如果你将函数属性分配给一个变量,如 x = o.start 并调用 x()内部启动不再引用 o 。当你执行 setTimeout 时会发生这种情况。为了使其有效,请改为:

Update: this object is not set based on declaration, but by invocation. What it means is that if you assign the function property to a variable like x = o.start and call x(), this inside start no longer refers to o. This is what happens when you do setTimeout. To make it work, do this instead:

 var o = new Request(...);
 setTimeout(function() { o.start(); }, 1000);

这篇关于'this'在JavaScript类方法中未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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