【问题标题】:Value of 'this' in JavascriptJavascript 中“this”的值
【发布时间】:2012-07-02 07:52:03
【问题描述】:

有人能解释一下为什么下面的“this”指向 DOM 对象而不是 Window 吗?

$("a").click(function() {
    console.log(this);
});

这会产生:

<a id="first" href="http://jquery.com">

考虑以下应该是相同的场景:

function Foo() {
    this.click = function(f) {
        f();
    }
}

var obj = new Foo();
obj.click(function() {
    console.log(this);
});

我们在这里得到的是 Window 对象(我所期望的)。

【问题讨论】:

  • jQuery 在需要的地方操作this
  • 像往常一样,MDN 对此有一些很好的信息:developer.mozilla.org/en/DOM/…
  • 我认为你应该问的人是 John Resig,据我所知,他负责这个概念 - 我相信这是他做的。信不信由你——但他也是an active member here。 :)

标签: javascript jquery this


【解决方案1】:

在 Javascript 中,OOP 与您在 Java 等语言中所习惯的不同。

基本上,更容易认为没有 OOP,this 只是函数的“隐藏参数”。

例如,当你看到

function f(x, y, z) {
    console.log(this, x, y, z);
}

认为在常见的 OOP 语言(如 Java)中会是

function f(this, x, y, z) {
    console.log(this, x, y, z);
}

当您看到var a = b.f(x, y, z); 时,想想var a = f(b, x, y, z)

当你看到var a = f(x, y, z);时想到var a = f(undefined, x, y, z);(在浏览器环境中,当strict mode没有被激活时,它是f(window, x, y, z);

现在应该更容易理解为什么您的示例中的 this 在嵌套范围中意味着不同的东西。

【讨论】:

    【解决方案2】:

    这取决于执行函数的上下文。 jQuery 显式更改回调函数的上下文,而您的函数在全局上下文中执行函数。

    改变上下文:

    function Foo() {
        this.click = function(f) {
            f.apply(this);
        }
    }
    

    function Foo() {
        this.click = function(f) {
            this.f = f
            this.f();
        }
    }
    

    进一步阅读:

    http://dailyjs.com/2012/06/18/js101-this/

    http://dailyjs.com/2012/06/25/this-binding/

    【讨论】:

    • 好答案 man :P this 也指被调用的 DOM 上的当前元素。 +1 代表
    【解决方案3】:

    this 将由上下文决定。

    如果您将代码更改为以下代码,则this 将指向some_other_object

    function Foo() {
        this.click = function(f) {
            f.call(some_other_object);
        }
    }
    

    【讨论】:

      【解决方案4】:

      jQuery 在调用事件处理程序时使用 javascript apply 函数。来自 mdn 文档:

      使用给定的 this 值和作为数组提供的参数调用函数。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多