See the following piece of simplified code:
myVar= 1;
myFunc = function() {
return { val : myVar };
};
myInstantiation = new myFunc();
console.log(myInstantiation ); //{val:1}
console.log(myVar); //1
myVar=2;
console.log(myInstantiation );//{val:1}
console.log(myVar); //2
is there any way I can declare the myInstantiation, or the myFunc so as to still do the same thing ( eg instantiate the object ) but in such a way that will allow me to change the myVar and have that change reflect inside the myInstantiation ?
Eg I want the output to be
console.log(myInstantiation );//{val:2}
console.log(myVar); //2
Not directly, no (well, you can with ECMAScript5). The expression
…takes the value of
myVarand assigns it to thevalproperty of a new object. There is no enduring connection between thatvalproperty’s value and the value of themyVar.The straightforward way to do what you want is to make
vala function rather than a property:Live example
If it has to be a property, it’s possible with ECMAScript5: You can define a function that gets called when someone accesses an object property, using the new
Object.definePropertyfunction:Live example – run in Chrome, a recent version of Firefox, or a recent Safari (but not Opera or any version, so far, of IE).
It’s still a function call, with the overhead that implies, but the code using
myInstantiationsees it as a property access. (Which is handy, but in some ways misleading.)Object.definePropertyonly works with JavaScript engines that support the new ECMAScript5 features, so notably not IE. There’s no standard way of doing what you’re doing without an explicit function call otherwise (Mozilla had done their own thing prior to the standard, but that’s now deprecated and only worked in a couple of browsers).There are some issues with your code that I should I should point out:
You’re not declaring your variables, and so you’re falling prey to the Horror of Implicit Globals.
Your
myFuncis defined as:…but then you’re calling it with
new:Since your function returns an object,
newserves no purpose there, you can just doThis is because of the way
newworks: It creates an object, initializes that object with a prototype frommyFunc.prototype, and then callsmyFuncwiththisset to the new object. IfmyFuncdoesn’t return anything or returns a primitive type (ornull), the result of thenewexpression is the new object thatnewcreated. But ifmyFuncreturns an object (as yours does), the new object created bynewis thrown away and your object is used instead. Sonewwith a function like yours is irrelevant.