为什么我在Javascript中丢失了这个上下文? [英] Why do I lose the context of this in Javascript?

查看:70
本文介绍了为什么我在Javascript中丢失了这个上下文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个简单的代码:

var o = {
    a: 1,
    b: 2,
    f1: function ()
    {
        alert(this.b);
    }
}

var o2 = {
    a: 11,
    b: 22,
    f2: function (j)
    {
        j();
    }
}

但运行此代码:

o2.f2(o.f1)产生 undefined 。 (虽然因此我期待22)

o2.f2(o.f1) yields undefined. ( while im expecting "22" as a result)

现在,我知道背景已经到了某个地方。因此,如果我将 o2 中的代码更改为:

Now, I know that the context has gone somewhere. and hence If I change the code in o2 to :

 f2: function (j)
    {
        j.apply(this);
    }

它确实有效。

但我的问题是:


  • 我在哪个阶段失去了背景?

我不明白:当 j()正在运行时,那里 o 对象中的 b 属性。

I don't understand : when j() is running , there is a b property in the o2 object.

我缺少什么?

jsbin

jsbin

推荐答案

我发现Crockford对这种方式有很好的描述作品。 JavaScript中的函数可以用4种样式调用:

I found Crockford had an excellent description of the way this works. Functions in JavaScript can be invoked in 4 styles :


  1. 函数样式

  2. 方法style

  3. 构造函数样式

  4. 调用或应用样式。

  1. The "function" style
  2. The "method" style
  3. The "Constructor" style
  4. The "call or apply" style.

我可能会在那里得到确切的名字,但精神是一样的。如果你没有,你肯定会得到JavaScript:The Good Parts这本书。

I might be getting the exact names wrong there, but the spirit is the same. You should definitely get the book "JavaScript: The Good Parts" if you don't have it.

所以无论如何 - 关于你的问题。关键是this的值取决于您使用的样式。

So anyway - on to your question. The key thing is that the value if "this" is dependant on which style you use.

// function invocation style, 
var f = function() { console.debug(this); }
f(); // "this" is bound to the global object.

// "method" invocation style
var obj = {
    f: function() { console.debug(this); }
};

obj.f(); // "this" is bound to "obj", the object on which the function was invoked

// so important bit is :

var f = obj.f;
f(); // "this" is global object
obj.f() // "this" is obj

在你的例子中,由于调用函数的方式,你正在失去this。

In your example you are losing "this" because of the way you are invoking the function.

这篇关于为什么我在Javascript中丢失了这个上下文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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