简体   繁体   English

如何将全局范围变量引用到本地范围?

[英]How to reference a global scope variable into the local scope?

var b=1;

function someFunc(b) {
     //here 
}

I want to be able to reference the variable b that is defined outside the function. 我希望能够引用在函数外定义的变量b。 How can this be done in javascript? 怎么能在javascript中完成?

You need to access it via the global object , which is window in a browser and global in node.js for instance. 您需要通过global object访问它,例如,浏览器中的window和node.js中的global window

var b=1;

function someFunc(b) {
    alert( window.b ); // or console.log( global.b );
}

Why ? 为什么? Well, the such called Activation Object (in ES3) or the Lexical Environment Record (ES5) will overlap the variable name b . 那么,所谓的激活对象 (在ES3中)或词汇环境记录 (ES5)将与变量名称b重叠。 So anytime a JS engine resolves b it'll stop at the first occurence, which is in its own Scope. 因此,只要JS引擎解析b它就会在第一次出现时停止,这是在它自己的Scope中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM