使用this或声明变量之间有什么区别var?
var foo = 'bar'
Run Code Online (Sandbox Code Playgroud)
要么
this.foo = 'bar'
Run Code Online (Sandbox Code Playgroud)
你this何时使用var?何时使用?
编辑:有一个简单的问题作出决定时,我可以问我自己,如果我想使用var或this
CMS*_*CMS 13
如果它是全局代码(代码不是任何函数的一部分),那么您将使用两个片段在全局对象上创建属性,因为this在全局代码中指向全局对象.
这种情况的不同之处在于,使用该var语句时,无法删除该属性,例如:
var foo = 'bar';
delete foo; // false
typeof foo; // "string"
this.bar = 'baz';
delete bar; // true
typeof bar; "undefined"
Run Code Online (Sandbox Code Playgroud)
(注意:上面的代码片段在Firebug控制台中的行为会有所不同,因为它使用eval运行代码,并且在Eval代码执行上下文中执行的代码允许删除用var其创建的标识符,请在此处尝试)
如果代码是函数的一部分,您应该知道this关键字与函数作用域无关,是隐式设置的保留字,具体取决于函数的调用方式,例如:
1 - 当函数作为方法调用时(该函数作为对象的成员调用):
obj.method(); // 'this' inside method will refer to obj
Run Code Online (Sandbox Code Playgroud)
2 - 正常的函数调用:
myFunction(); // 'this' inside the function will refer to the Global object
// or
(function () {})();
Run Code Online (Sandbox Code Playgroud)
3 - 使用新运算符时:
var obj = new Constructor(); // 'this' will refer to a newly created object.
Run Code Online (Sandbox Code Playgroud)
您甚至可以this使用call和apply方法显式设置值,例如:
function test () {
alert(this);
}
test.call("hello!"); //alerts hello!
Run Code Online (Sandbox Code Playgroud)
您还应该知道JavaScript只有函数作用域,并且使用该var语句声明的变量只能在同一函数或下面定义的任何内部函数中访问.
编辑:查看您发布到@ David的答案的代码,让我评论:
var test1 = 'test'; // two globals, with the difference I talk
this.test2 = 'test'; // about in the beginning of this answer
//...
function test4(){
var test5 = 'test in function with var'; // <-- test5 is locally scoped!!!
this.test6 = 'test in function with this'; // global property, see below
}
test4(); // <--- test4 will be called with `this` pointing to the global object
// see #2 above, a call to an identifier that is not an property of an
// object causes it
alert(typeof test5); // "undefined" since it's a local variable of `test4`
alert(test6); // "test in function with this"
Run Code Online (Sandbox Code Playgroud)
您无法访问test5函数外部的变量,因为它是本地作用域的,并且只存在该函数的作用域.
编辑:回复您的评论
为了声明变量,我鼓励你总是使用var它,这就是为它做的.
this当您开始使用构造函数,对象和方法时,值的概念将变得有用.