我看到一些看起来像这样的代码:
function foo(bar) {
this.bar = bar;
};
Run Code Online (Sandbox Code Playgroud)
你可以像这样重写它:
function foo(bar) {
var bar = bar;
};
Run Code Online (Sandbox Code Playgroud)
因为那样你就不需要继续写this更好的了.这两行代码是否做同样的事情?
非常感谢.
eme*_*esx 11
this这将创建对象的属性.它是公共的,具有读写访问权限.根据函数的调用方式(使用new?),this将指向不同的对象. 更多关于这个问题.
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
Run Code Online (Sandbox Code Playgroud)
var这会创建一个局部变量(注意:变量已经通过函数参数在范围内).这是本地的,只能从foo函数的范围访问.
function foo(bar) {
var bar = bar;
}
Run Code Online (Sandbox Code Playgroud)
除非你写oo js,否则你可能想要坚持第二种选择,甚至更好 - 跳过bar任何重新定义.您可以获得封装的所有常见好处.
function foo(bar) {
// just use argument bar
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
89 次 |
| 最近记录: |