Sat*_*ish 1 javascript node.js
下面是一个我想要了解的简单的JavaScript OOP.我想知道为什么getA()并getC()返回undefined,但是getB()当我B在构造函数中更改变量并将其分配给时,同样返回2 b.
当我运行getD()它返回时,我指的是什么?怎么this在这里工作?
var a,b,c,d;
var encap = function(a,B,c,d){
a = a;
b = B;
this.c = c;
this.d = d;
}
encap.prototype.getA = function() {
return a; // returns undefined
};
encap.prototype.getB = function() {
return b; // returns 2
};
encap.prototype.getC = function() {
return c; // undefined
};
encap.prototype.getD = function() {
return this.d;
};
encap.prototype.setA = function(A) {
a = A;
};
encap.prototype.setB = function(B) {
b = B;
};
var encapObj = new encap(1,2,4,6);
console.log(encapObj.getA()); // undefined
console.log(encapObj.getB()); // 2
console.log(encapObj.getC()); // undefined
console.log(encapObj.getD()); // 6
Run Code Online (Sandbox Code Playgroud)
a = a;
Run Code Online (Sandbox Code Playgroud)
这会a从局部变量中分配局部变量a,有效地(无效地)无所事事.全局变量仍设置为它的默认undefined,这就是为什么你undefined的getA().
在getC(),您返回全局变量的值c,但仅分配给c实例的属性:this.c.this在JavaScript中不是隐含的.
| 归档时间: |
|
| 查看次数: |
130 次 |
| 最近记录: |