首先使用var
function testCode(some)
{
var something = some;
}
第二次使用这个
function testCode2(some)
{
this.something = some ;
}
最佳答案
在第一个函数中,something
是一个private(局部)变量,这意味着它在函数外是完全不可访问的;而在第二个中,它是一个 public 实例变量。设置变量的上下文将取决于您调用函数的方式:
> testCode2("foo"); // this will refer to document.window
> something
"foo"
>> var obj = new testCode2("foo"); // this will refer to the new object
>> something
ReferenceError: something is not defined
>> obj.something
"foo"
引用:
- Private Members in JavaScript , 道格拉斯·克罗克福德
关于javascript - 'var' 声明的变量和 'this' 在 Javascript 中创建的属性有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12094676/