JavaScript的嵌套函数失去范围 [英] Javascript nested function losing scope

查看:118
本文介绍了JavaScript的嵌套函数失去范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释的范围如下code的结合,请

Can someone explains the scope binding of the following code please

window.name = "window";

object = {
       name: "object",
       method: function() {
             nestedMethod: function() {
                   console.log(this.name);
             }
             nestedMethod();
       }
}

object.method();  // print 'window'

我想我的问题是更多关于这个 ...为什么这个失去范围,默认为全球范围内?尽我们创造将继续在全球范围内?匿名函数

I think my question is more about this...why is this losing the scope and default to the global scope ? do all the anonymous functions that we created will go on the global scope ?

推荐答案

当你调用一个函数,只需书写 FUNC()在函数内部将指向全局对象。你的情况,你写的:

Whenever you call a function, simply by writing func(), this inside the function will point to the global object. In your case you write:

nestedMethod();

所以这个 nestedMethod 是窗口对象。您可以使用呼叫(或适用)手动定义上下文为你函数调用:

So this inside nestedMethod is the window object. You can use call (or apply) to manually define a context for you function call:

nestedMethod.call(this);

这篇关于JavaScript的嵌套函数失去范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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