javascript - 这与class对象中的var之间的区别

时间:2014-05-18 08:38:35

标签: javascript

想知道以下代码中变量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中提取值。

2 个答案:

答案 0 :(得分:4)

  1. test1myClass函数的本地变量。它不能在外面访问。

  2. test2是调用myClass的当前对象的属性。

  3. 基于函数名称中包含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声明的变量的范围是它的当前执行上下文,它是封闭函数,或者对于在任何函数外部声明的变量,是全局的。