javascript多维对象
我试图使用以下代码在 JavaScript 中定义一个多维对象:
function A(one, two) {
this.one = one;
this.inner.two = two;
}
A.prototype = {
one: undefined,
inner: {
two: undefined
}
};
A.prototype.print = function() {
console.log("one=" + this.one + ", two=" + this.inner.two);
}
var a = new A(10, 20);
var b = new A(30, 40);
a.print();
b.print();
结果是:
one=10, two=40
one=30, two=40
,但我期望
one=10, two=20
one=30, two=40
我做错了什么? 变量inner
是类变量,而不是实例吗?
JavaScript 引擎:Google V8。
I'm trying to define a multidimensional object in JavaScript with the following code:
function A(one, two) {
this.one = one;
this.inner.two = two;
}
A.prototype = {
one: undefined,
inner: {
two: undefined
}
};
A.prototype.print = function() {
console.log("one=" + this.one + ", two=" + this.inner.two);
}
var a = new A(10, 20);
var b = new A(30, 40);
a.print();
b.print();
The result is:
one=10, two=40
one=30, two=40
, but I expect
one=10, two=20
one=30, two=40
What am I doing wrong?
Is a variable inner
a class variable, not an instance?
JavaScript engine: Google V8.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为
inner
的对象字面量为所有实例共享。它属于原型
,因此每个实例共享相同的对象。为了解决这个问题,您可以在构造函数中创建一个新的对象文字。Because the object literal for
inner
gets shared for all instances. It belongs to theprototype
and thus every instance shares the same object. To get around this, you can create a new object literal in the constructor.inner
部分是一个全局对象,未绑定到一个实例。The
inner
part is a global object not bound to one instance.