了解Javascript的OOP:修改其他实例的实例 [英] Understanding Javascript's OOP: instances modifying other instances
问题描述
我很难理解为什么修改实例a
中的属性会修改实例b
上的相同属性.
I'm having some trouble understanding why modifying a property in instance a
modifies the same property on instance b
.
var A = function (){
};
A.prototype.data = {
value : 0
};
var a = new A();
var b = new A();
console.log(a.data.value, b.data.value); // 0, 0
a.data.value = 5;
console.log(a.data.value, b.data.value); // 5, 5
prototype关键字不应该将data
变量设置为实例变量吗?
Shouldn't the prototype keyword make the data
variable an instance variable ?
在按照预期执行的示例中,情况似乎并非如此:
This seems not to be the case in this example which executes as expected:
var B = function (){
this.data = {
value : 0
};
};
var i = new B();
var j = new B();
console.log(i.data.value, j.data.value); // 0, 0
i.data.value = 5;
console.log(i.data.value, j.data.value); // 5, 0
我很困惑为什么原型方法不起作用.也许我缺少一些概念性知识.
I'm confused as why the prototype method wont work. Maybe i'm lacking some conceptual knowledge.
推荐答案
js中的原型是该类所有实例之间的数据共享,就像经典oop语言中的静态变量一样.有时在.prototype中放置一些方法/字段以节省运行时的内存很有用.
Prototype in js is a data shared between all instances of that class, it's like a static variable from classic oop languages. Sometimes it's usefull to put some methods/fields in .prototype to save memory on runtime.
这篇关于了解Javascript的OOP:修改其他实例的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!