How do you specify variables in javascript?

I want to give a link to variables in javascript.

For example, I want:

a=1 b=a a=2 

and have b = 2 and change accordingly to a.

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

What I wanted to do was makeobject function, which creates an object and puts it in an array, and returns it as

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

so i can do

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

and then in the do code

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

as well as change the values ​​of a, b and c

+4
source share
3 answers

You can disable this 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; } }; oa = 2; ob = 3; oa = 4; alert(ob); // 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(ob); 
+5
source

It is possible. However, you will have to use an object:

 var a = new Object(); a.val = 6; alert(a.val); var b = a; b.val = 5; alert(a.val); 

Edit: I played with another alternative (although the answer has already been noted), but here is another solution:

 function makeobj() { if(typeof makeobj.baseobj === 'undefined') { makeobj.baseobj = { 'blah': 'whatever', 'foo': 8 }; } return makeobj.baseobj; } var a = makeobj(); var b = makeobj(); var c = makeobj(); alert(a['blah']); alert(b['blah']); alert(c['blah']); b['blah'] = 'i changed the value'; alert(a['blah']); alert(b['blah']); alert(c['blah']); 

An alternative solution will allow you to create n objects and change values ​​whenever you want, and the changes apply to other variables created by the makeobj() function.

+2
source

It's impossible.

What are you trying to do?
We can probably find you more Javascript-y features.

0
source

Source: https://habr.com/ru/post/1335014/


All Articles