为什么“show”方法无法访问此处的“text”变量?
// @constructor A
var A = function(){
//alerts some text variable
this.show = function(){
alert("Hello")
alert(text);
}
}
//@constructor B
var B = function(){
//local text variable
var text = "World";
A.apply(this); // "show" method will get attached to B
}
var obj = new B();
//now calling show of B's object.
obj.show(); //returns error.
//Expected output
alerts "Hello"
alerts "World"
//Actual output
alerts "Hello"
ReferenceError: text is not defined
我在这里遗漏了什么吗? B 的“show”方法不应该访问“text”变量吗?
最佳答案
与 C++ 或 Java 不同,Javascript 没有隐式 this
。
如果函数(如 show
)引用 this.foo
,则仅 this
的值取决于函数的调用方式.
但是,如果 show
直接引用变量(如 foo
),那么它可能意味着:
- 局部变量,如果它是在函数范围内使用
var
定义的; - 闭包中的变量,如果该函数是在另一个函数中定义的,而该函数恰好用
var
定义它(闭包是在函数定义时创建的), - 否则为全局变量。
对于您的情况,适用第三种情况。 show
无法访问 text
,因为它是在完全不相关的范围中定义的。
关于javascript - 在 Javascript 中使用带有 "apply"的局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21650165/