gpt4 book ai didi

javascript - 函数内部的 javascript 函数是全局作用域的吗?

转载 作者:行者123 更新时间:2023-12-03 18:40:48 24 4
gpt4 key购买 nike

这是我做的测试的一个例子:

function f1(var1){
alert('f1 called');
function f2(var2){
alert('f2 called');

}
this.data='something else';
this.f2 = f2;
}
f1.data='something';
f1.f3 = function(var3){
alert('f3 called');
}
console.log(f1); //shows the function
console.log(f1.data); //can have properties attached - cool
console.log(f1.f2(2)); //error: "f1.f2" is not a function
console.log(f1.f3(3)); //this works as expected

看起来 f1 中的函数 f2 在范围内是局部的。是否有任何等效的方法可以在这样的函数内调用函数?

最佳答案

不幸的是,this 绑定(bind)到 window 的全局范围,因为您还没有使用 new 实例化 f1 的实例f1();

var f = new f1();
f.f2(); // Now works

关于javascript - 函数内部的 javascript 函数是全局作用域的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42346719/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com