[英]Javascript class encapsulation behaviour
Can somebody explain me this javascript behaviour? 有人可以向我解释这种JavaScript行为吗? I create 2 objects ( x
, y
) and I call xm()
to modify private variable b
on x
. 我创建2个对象( x
, y
),然后调用xm()
修改x
上的私有变量b
。 Then I call printing methods on both x
and y
and it produces following output. 然后,我在x
和y
上调用打印方法,并产生以下输出。 The output differs if the printing method p()
is defined as a this
property (1) or as a prototype (2). 如果将打印方法p()
定义this
属性(1)或原型(2),则输出将不同。
this.p
definition acts as expected: 2 objects have two private variables, modifying b
property on x
does not affect y
's b
property. this.p
定义作为预期:2级的对象有两个私有变量,修改b
财产x
不影响y
的b
属性。 But with A.prototype.p
definition, b
property seems to be static variable common for both objects x
and y
. 但是使用A.prototype.p
定义, b
属性似乎是对象x
和y
A.prototype.p
静态变量。
Described behaviour in code: 代码中描述的行为:
function A() {
var b = "bbb";
function f() {
b = "ccc";
}
// 1)
this.p = function() {
console.log(b);
};
// 2)
//A.prototype.p = function() {
// console.log(b);
//};
A.prototype.m = function() {
f();
};
}
var x = new A();
var y = new A();
x.m();
x.p();
y.p();
produces: 生产:
// 1)
bbbb
ccc
// 2)
//ccc
//ccc
In your example, you are overriding the prototype method p
(as well as m
) in the constructor of A
, which means every time you create an instance the prototype method will change. 在您的示例中,您将覆盖A
的构造函数中的原型方法p
(以及m
),这意味着每次创建实例时,原型方法都会更改。 All instances of A
will then use the same method, which is the one of the last created instance. 然后, A
所有实例将使用相同的方法,这是最后创建的实例之一。
Have a look at this example which should show the behaviour you expect for your code: 看一下此示例,该示例应显示您期望的代码行为:
function A() {
this.b = "bbb";
}
A.prototype.p = function() {
console.log(this.b);
};
A.prototype.m = function() {
this.b = "ccc";
};
var x = new A(),
y = new A();
x.m();
x.p();
y.p();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.