如何在函数内部的全局上下文中定义 javascript 中的函数?
How define function in javascript in global context inside a function?
context = this
function test() {
(function(cmd) {
eval(cmd);
}).call(context, 'function foo(){}');
};
test();
foo(); // => ReferenceError: foo is not defined
如何在函数内部定义全局函数? (使用 nodeJS)
访问全局对象的典型方法是调用产生的值,例如来自逗号运算符。
function a() {
(0, function () {
this.foo = function () { console.log("works"); };
})();
}
a();
foo();
更新:
由于strict mode
问题,这里是另一个版本(参考:(1,eval)('this') vs eval('this') in JavaScript?, Cases where 'this' is the global Object in Javascript):
"use strict";
function a() {
(0, eval)('this').foo = function () { console.log("works"); };
}
a();
foo();
在Node.JS中使用global
对象:
function test() {
eval('function foo() { return "this is global"; }');
global.foo = foo;
};
test();
console.log(foo()); // this is global
context = this
function test() {
(function(cmd) {
eval(cmd);
}).call(context, 'function foo(){}');
};
test();
foo(); // => ReferenceError: foo is not defined
如何在函数内部定义全局函数? (使用 nodeJS)
访问全局对象的典型方法是调用产生的值,例如来自逗号运算符。
function a() {
(0, function () {
this.foo = function () { console.log("works"); };
})();
}
a();
foo();
更新:
由于strict mode
问题,这里是另一个版本(参考:(1,eval)('this') vs eval('this') in JavaScript?, Cases where 'this' is the global Object in Javascript):
"use strict";
function a() {
(0, eval)('this').foo = function () { console.log("works"); };
}
a();
foo();
在Node.JS中使用global
对象:
function test() {
eval('function foo() { return "this is global"; }');
global.foo = foo;
};
test();
console.log(foo()); // this is global