改变JavaScript的全局对象

改变JavaScript的全局对象

本文介绍了改变JavaScript的全局对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在JavaScript中更改 root 对象?

Is there a way to change the root object in JavaScript?

例如,在浏览器中, root 对象是窗口。所以

For example, in browsers, the root object is "window". So

X = 5;
console.log(Y);

与以下内容相同:

window.X = 5;
console.log(window.Y);

我现在要做的是改变这个 root 对象,所以当我执行以下操作时:

What I want to do now, is changing this root object, so when I do the following:

X = 6;

我需要这个的原因:

在应用程序中,程序的每个部分可以访问全局对象。这是一个大问题,因为Node.js网络服务器执行的每个脚本都可以向其添加新变量。他们将在那里,直到重新启动网络服务器。我希望通过更改全局对象来避免这种情况。

In Node.js applications, every part of the program can access the global object. That's a big problem because every script that is executed by a Node.js webserver can add new variables to it. They will be there until the webserver is restarted. I want to avoid this by changing the global object.

更新

我已经测试了下面的代码并得到了一个非常有趣的结果。
您对以下代码的期望是什么?

I've tested the following code and got a really interesting result.What did you expect of the following code?

var X = {A:"a",B:"b"};

with(X){
    A = 5;
    C = 7;
}
for(a in X){
    console.log(a+" is "+X[a]);
}

/*
Expected Console Output:
A is 5
B is b
C is 7

Real Console Output:
A is 5;
B is b;

*/

有没有办法像我预期的那样获得输出?

Is there a way to get output as I expected it?

更新

我现在用以下方法测试了模块系统代码。

I've now tested the module system with the following code.

//program.js
var t = require("./module.js");
t.Test();

console.log(A);

//module.js
A = 5;
exports.Test = function(){
    console.log("hello world!");
}

输出为:

hello world!
5

这告诉我,<$ c $中定义的变量A c> module.js 已添加到 program.js 的全局对象中。该模块也没有解决我的问题。

This tells me, that the variable "A" defined in module.js was added to the global object of program.js. The module does not solve my problem, either.

推荐答案

有一个 statement,但不建议在严格模式下禁止。

There is the with statement, but it is not recommended and forbidden in strict mode.

最好明确地引用保存对象的变量。

It is better to refer to the variable holding the object explicitly.

回应更新的问题:

with 将搜索范围链,直到找到具有匹配属性的对象或者到达 window 。对于在对象上定义新属性没有好处。

with will search up the scope chain until it finds an object with a matching property or gets to window. It is no good for defining new properties on an object.

var X = { A: 5, B: 8, C: 7};
with(X){
    console.log(A, B, C);
}

这篇关于改变JavaScript的全局对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 23:12