我不知道这是否可行,但是假设我们有以下代码:
var name = 'John';
function log() {
console.log('Hello ' + name );
}
function greetTravis() {
var name = 'Travis';
log(); // This function is defined outside greetTravis's scope.
}
greetTravis();
log();
结果:
Hello John // Is there a workaround to get "Hello Travis"?
Hello John
硬编码解决方案:(我不想重复自己)
var name = 'John';
function log() {
console.log('Hello ' + name );
}
function greetTravis() {
var name = 'Travis';
log(); // Now, it is defined inside greetTravis's scope.
function log() {
console.log('Hello ' + name );
}
}
greetTravis();
log();
我追求的是:
我想在不传递变量的情况下从日志函数访问名称变量(greetTravis() 中的那个),也许使用改变 log() 范围的函数,例如:调用/绑定(bind)。
Note: call and bind functions allow you to change the context (this) not the scope .
最佳答案
对于您想要的结果,您只需重构 log
以便它采用您希望它记录的名称。
仅供引用 - window
对象有一个名为 name
的属性。因此,最好不要在代码中将 name
用作 Global。
var userName = 'John';
function log(val) {
console.log('Hello ' + val );
}
function greetTravis() {
var userName = 'Travis';
log(userName); // This function is defined outside greetTravis's scope.
}
greetTravis();
log(userName);
关于javascript - 是否可以在 Javascript 中以编程方式更改词法范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51953812/