你如何在javascript中给变量引用? [英] How do you give variables reference in javascript?

查看:49
本文介绍了你如何在javascript中给变量引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 javascript 中给变量引用.

I want to give variables reference in javascript.

例如,我想做:

a=1
b=a
a=2

并使 b=2,并相应地更改为 a.

and have b=2, and change accordingly to a.

这在javascript中可行吗?如果不是,有没有办法像 a.onchange = function () {b=a} 那样做?

Is this possible in javascript? If it isn't is there a way to do like a.onchange = function () {b=a}?

我想做的是创建一个类似于 makeobject 的函数,它创建一个对象并将其放入一个数组中,然后像这样返回它

What I wanted to do was make a function like makeobject which make an object and puts it in an array and than returns it like

function makeobject() {
   objects[objects.length] = {blah:'whatever',foo:8};
   }

我做不到

a=makeobject()
b=makeobject()
c=makeobject()

然后在代码中做

for (i in objects) {
   objects[i].blah = 'whatev';
}

同时改变a、b和c的值

and also change the values of a,b and c

推荐答案

您可以使用适用于大多数浏览器的新对象字面量语法实现这一点.

You can pull this off using the new object literal syntax which works well in most browsers.

var o = {
    _a : null,
    get a() { return this._a; },
    set a(v) { this._a = v; },
    get b() { return this._a; },
    set b(v) { this._a = v; }
};

o.a = 2;
o.b = 3;
o.a = 4;
alert(o.b); // alerts 4

另一种选择是创建您自己的参考对象.

Another alternative is to create your own reference object.

function Ref(obj, name, otherName) {
    this.obj = obj;
    this.name = name;
    this.otherName = otherName;
}

Ref.prototype.assign = function (v) {
    this.obj[this.name] = this.obj[this.otherName] = v;
}

var o = {
    a : 1,
    b : 4
};

var ref = new Ref(o, 'a', 'b');
ref.assign(3);

alert(o.b);

这篇关于你如何在javascript中给变量引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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