javascript多维对象 [英] javascript multidimensional object

查看:79
本文介绍了javascript多维对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下代码在JavaScript中定义多维对象:

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();

结果是:

one=10, two=40
one=30, two=40

,但我希望

one=10, two=20
one=30, two=40

我做错了什么?
变量是内部一个类变量,而不是一个实例?

What am I doing wrong? Is a variable inner a class variable, not an instance?

JavaScript引擎:Google V8。

JavaScript engine: Google V8.

推荐答案

因为所有实例都共享 inner 的对象文字。它属于原型,因此每个实例共享同一个对象。要解决这个问题,您可以在构造函数中创建一个新的对象文字。

Because the object literal for inner gets shared for all instances. It belongs to the prototype and thus every instance shares the same object. To get around this, you can create a new object literal in the constructor.

这篇关于javascript多维对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆