使用javascript对象原型扩展类时遇到问题 [英] Problem extending class with javascript object prototype
问题描述
我遇到了这个问题... B是基类,而A是派生类...尽管A是从B派生的,但A的各种对象都指向B的同一对象.
I have got this problem... B is a base class, and A is a derived class... Event though A is derived from B, various objects of A points to the same object of B.
我知道我已经将B的对象分配给A的原型,以使B成为子代.
I know i have assigned an object of B to the prototype of A to make A child of B.
但是A的不同对象,它们应该具有不同的地址空间来容纳变量,对吗?有人可以纠正吗?
But different objects of A, they should have different address space to hold the variables, right? Can you anyone correct this?
function B(){
this.obj = {};
}
function A(){
}
A.prototype = new B();
var a = new A();
var b = new A();
var c = new A();
console.log(a.obj == b.obj); //prints true
console.log(a.obj === b.obj); //prints true
a.obj.name = "stackoverflow";
console.log(b.obj.name); //prints stackoverflow
我应该对这段代码进行哪些更改,以便获得以下结果.
What change should I make in this code so that gives me following result.
a.obj === b.obj //must be false
a instanceof A; //must be true
a instanceof B; //must be true
推荐答案
这就是为什么您不应该在原型上具有可变值(尤其是对象或数组)的原因-相同的值将在所有对象实例之间共享,并且可以更改在任何一个.在这里,您可以使用 Object.create 来避免此问题创建原型时不要调用B
的构造函数:
That's why you shouldn't have mutable values (particularly objects or arrays) on a prototype - the same value will be shared across all object instances and can be changed in any of them. Here you can avoid the problem by using Object.create that won't call the constructor of B
when creating the prototype:
A.prototype = Object.create(B.prototype);
A
的构造函数然后应为每个新对象调用B
的构造函数:
Constructor of A
should then call the constructor of B
for each new object:
function A() {
B.call(this);
}
对于不支持Object.create()
的浏览器,您可以按照 http://javascript中提到的进行仿真.crockford.com/prototypal.html .
For browsers that don't support Object.create()
you can emulate it as mentioned on http://javascript.crockford.com/prototypal.html.
这篇关于使用javascript对象原型扩展类时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!