“此”的范围在JavaScript中 [英] Scope of "this" in JavaScript

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

问题描述

我有一个如下所示的JavaScript类:

I have a JavaScript class that looks like this:

function SomeFunction()
{
    this.doSomething(function()
    {
        this.doSomethingElse();
    });

    this.doSomethingElse = function()
    {

    }
}

此代码抛出一个错误,因为传递给doSomething()的函数内部的this范围与该函数外部的this范围不同。

This code throws an error because the scope of "this" inside the function that is passed into doSomething() is different that than the scope of "this" outside of that function.

我理解为什么会这样,但是处理这个问题的最佳方法是什么?这就是我最终要做的事情:

I understand why this is, but what's the best way to deal with this? This is what I end up doing:

function SomeFunction()
{
    var thisObject = this;

    this.doSomething(function()
    {
        thisObject.doSomethingElse();
    });

    this.doSomethingElse = function()
    {

    }
}

这很好,但它只是感觉像一个黑客。只是想知道某人是否有更好的方法。

That works fine, but it just feels like a hack. Just wondering if someone has a better way.

推荐答案

这位评论者有我想要的东西(虽然其他答案也很好) ):

This commenter had what I was looking for (although the other answers are good too):

@Jon Kruger看到这个,看看他们的文章也是如此: https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Function/Apply - Jonathon 44分钟前

@Jon Kruger See this, check out their article for call, too: https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Function/Apply– Jonathon 44 mins ago

这篇关于“此”的范围在JavaScript中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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