下面是我试图理解的一个简单的JavaScript OOP。我想知道为什么getA()和getC()返回未定义的,但是当我更改构造函数中的变量B并将其分配给b时,相同的getB()返回2。
当我运行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发布于 2014-08-21 20:38:10
在这里,我注释了每个赋值的变量被分配到哪里。
这应该有助于解释一些事情。
// Create four global variables.
var a,b,c,d;
var encap = function(a,B,c,d){
// Assign local argument a, to local argument a. Does nothing
a = a;
// Assign local argument "B" to global variable "b"
b = B;
// assign local argument 'c' to property 'c'
this.c = c;
// assign local argument 'd' to property 'd'
this.d = d;
}
encap.prototype.getA = function() {
// Returns global variable a
return a; // returns undefined
};
encap.prototype.getB = function() {
// Return global variable B, which was assigned in the constructor
return b; // returns 2
};
encap.prototype.getC = function() {
// Return global variable 'c'
return c; // undefined
};
encap.prototype.getD = function() {
// return object property 'd', which was assigned.
return this.d;
};
encap.prototype.setA = function(A) {
// assign global variable 'a' from argument 'A'
a = A;
};
encap.prototype.setB = function(B) {
// assign global variable 'b' from argument 'B'
b = B;
};
var encapObj = new encap(1,2,4,6);发布于 2014-08-21 20:31:28
a = a;这从局部变量a分配给局部变量a,有效(无效?)什么都不做。全局变量仍然设置为默认的undefined,这就是从getA()获得undefined的原因。
在getC()中,返回全局变量c的值,但只分配给实例的属性c:this.c。this并不隐含在JavaScript中。
发布于 2014-08-21 20:39:31
好吧,这么说吧。您有四个全局变量:
var a, b, c, d;还有四个变量是构造函数的本地变量。
var encap = function(a,B,c,d);然后还有两个“实例”变量--在创建新对象时附加到新对象的变量。
this.c = c;
this.d = d;在构造函数中,设置a = a -这实际上只是将局部变量(参数) a设置为自身。您正在从=两侧的构造函数中访问局部变量。在访问器getA中,返回全局变量a -它是未定义的。
同样,在构造函数中,您将全局变量b的值设置为局部变量B的值-请记住,它们是不同的,因为JavaScript是区分大小写的。因此,您的全局变量b现在的值为2。同样,由于您在访问器getB中返回全局变量,所以您将得到值2。
在访问器getC中,仍然返回全局变量c --它从未设置过。因此,undefined。但是,这一次在构造函数中设置了this.c,因此如果要在访问器中设置return this.c,则应该获得正确的值。
总之,您可能应该在所有变量赋值和返回中使用this。因此,构造函数应该如下所示:
var encap = function(a,B,c,d){
this.a = a;
this.b = B;
this.c = c;
this.d = d;
}您的访问器应该如下所示:
encap.prototype.getD = function() {
return this.d;
};从那以后,我觉得很明显你的策划人应该是什么样子。祝您在JavaScript中探索OOP时好运。这是我最喜欢的语言,我喜欢它的OOP,不管别人怎么说它。如果您有麻烦,StackOverflow JS聊天室通常是有帮助的,所以稍后再来吧。
https://stackoverflow.com/questions/25435357
复制相似问题