想知道以下代码中变量test1和test2之间的区别。
function myClass(){
var test1 = 'abc';
this.test2 = 'def';
this.Method1 = function(){
someObj(this.success);
}
this.success = function(){
console.log(test1); //able to output value
console.log(this.test2); //unable to get the output
console.log(test2); //unable to get the output
}
}
编辑:为了更精确,我试图从内部函数访问变量。我无法访问test2变量,但能够从test1中提取值。
答案 0 :(得分:4)
test1
是myClass
函数的本地变量。它不能在外面访问。
test2
是调用myClass
的当前对象的属性。
基于函数名称中包含Class
的事实,我假设它是一个构造函数。因此,test2
将在新构造的对象上设置。
答案 1 :(得分:0)
Functions and function scope (MDN)
关于范围的全部内容。这里有一个很好的例子和解释:What is the scope of variables in JavaScript?
JavaScript实际上只有2种类型,功能和全局。
在这种情况下, this.test2
与window.test2
相同。
this 关键字不引用当前正在执行的函数,因此您必须按名称引用Function对象,即使在函数体内也是如此。
var test1
只会在您的函数myClass
变量声明,无论它们出现在何处,都会在执行任何代码之前进行处理。用var声明的变量的范围是它的当前执行上下文,它是封闭函数,或者对于在任何函数外部声明的变量,是全局的。