我看到了一些看起来像这样的代码:
function foo(bar) {
this.bar = bar;
};
你能不能这样重写:
function foo(bar) {
var bar = bar;
};
因为这样您就不需要继续编写更好的this
。这两段代码做同样的事情吗?
非常感谢。
最佳答案
使用这个
这会创建一个对象的属性。它是公共(public)的,具有读写访问权限。根据调用函数的方式(使用 new
?),this
将指向不同的对象。 More on the subject here.
function foo(bar) {
this.bar = bar;
};
foo(10);
console.log(bar); // bar or this.bar .. prints 10
var tmp = new foo(20);
console.log(tmp.bar); // prints 20
console.log(bar); // still prints 10
使用var
这将创建一个局部变量(注意:该变量已通过函数参数在范围内)。这是本地的,只能从 foo
函数的范围内访问。
function foo(bar) {
var bar = bar;
}
什么时候用哪个?
除非您编写 oo js,否则您可能希望坚持使用第二个选项,甚至更好 - 跳过 bar
的重新定义。您将获得封装的所有常见好处。
function foo(bar) {
// just use argument bar
}
关于javascript - 这两个代码片段是否相同(使用 var 与使用 this),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15811968/