下面是我试图理解的一个简单的 JavaScript OOP。我想知道为什么 getA()
和 getC()
返回 undefined,但是同样的 getB()
在我更改变量时返回 2 B
在构造函数中并将其分配给 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
最佳答案
a = a;
这从局部变量 a
赋值给局部变量 a
,实际上(无效?)什么都不做。全局变量仍设置为其默认值 undefined
,这就是您从 getA()
获取 undefined
的原因。
在 getC()
中,您返回全局变量 c
的值,但只分配给实例的属性 c
: 这个.c
。 this
在 JavaScript 中不是隐含的。
关于JavaScript 面向对象。尝试在 JavaScript 中学习 OOP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25435357/