Dan*_*iel 5 javascript constructor var this
在我的上一个问题之后,这个对我来说更准确:
例:
function Foo() {
this.bla = 1;
var blabla = 10;
blablabla = 100;
this.getblabla = function () {
return blabla; // exposes blabla outside
}
}
foo = new Foo();
Run Code Online (Sandbox Code Playgroud)
我现在明白了:
this.bla = 1; // will become an attribute of every instance of FOO.
var blabla = 10; // will become a local variable of Foo(will **not** become an attribute of every instance of FOO), which could be accessed by any instance of FOO - only if there's a method like "this.getBlabla". that's a "closer" ?
blablabla = 100; // will define a **new** (or change if exist) global(window) variable.
Run Code Online (Sandbox Code Playgroud)
我理解正确吗?
此外 - 如果我在承包商中包含var blabla = 10;和getblabla使用它的功能,那么对于Foo的每个实例("foo"......),将在内存中保存包含此"私有"变量的Foo承包商功能.或者它是否与私有变量的位置相同 - 对于Foo的所有实例(如"foo")?
只关注范围,我将通过这个例子,(更清晰的变量)然后,我将它连接回你的变量.
var x = "Global scope";
var y = "Not changed.";
function Foo() {
this.x = "Attribute of foo";
var x = "In foo's closure";
y = "Changed!"
this.getX = function () {
return x;
}
}
// do some logging
console.log(x); // "Global scope"
console.log(y); // "Not changed"
foo = new Foo();
console.log(y); // "Changed!"
console.log(foo.x); // "Attribute of foo"
console.log(x); // "Global scope"
console.log(foo.getX()); // "In foo's closure"
Run Code Online (Sandbox Code Playgroud)
行:this.x等同于this.bla,它定义了Foo对象的外部可用属性.y相当于blablabla=100,然后x内部foo相当于你的blablabla内部foo.这是一个非常粗略的jsfiddle你可以运行来看到这一点.
| 归档时间: |
|
| 查看次数: |
5589 次 |
| 最近记录: |