Ok, I try to create new object this way:
var src = {a:'a', b:'b', c:'c'};
var out = {};
for(var prop in src){
Object.defineProperty(out, prop,{
get: function(){
return src[prop];
},
set: function(val){
src[prop]=val;
}
})
}
And get a bad result:
out = {a:'c', b:'c', c:'c'}
I know other ways to create this object, so as:
for (var prop in src) {
(function(prop) {
Object.defineProperty(out, prop, {
get: function() {
return src[prop];
},
set: function(val) {
src[prop] = val;
}
})
})(prop)
}
or:
Object.keys(src).map(function(prop){
Object.defineProperty(out, prop,{
get: function(){
return src[prop];
},
set: function(val){
src[prop]=val;
}
})
})
But I can't understand why, in the first method, a string parameter "prop" will be sent to the function 'defineProperty' by link. Help me to understand this please.
Sorry for bad english.
When you create a function inside a loop you create a closure around the variables used in that loop. In this case there is a closure around prop. Each function (the getters) has a reference to prop so when they are called later on (when the getter is used) they use the value in prop which happens to be the last value that was assigned in the loop.
In other words, since the getter is called later, the value in prop is whatever value it was last set to. defineProperty, on the other hand, gets the correct value since there is no closure. It is called with the value at the time of the call rather than after the loop is complete.
Related
When using:
Object.defineProperty(obj,prop,desc){
get: function(){...
set: function(){...
}
Does the getter/setter apply to obj[prop] or does it act on obj no matter what property is specified?
I am asking because I'm trying to setup some data binding based on a nested object like:
obj[propA] = {propB:'seomthing',propC:'somethingElse'}
and when I do something like this:
var obj = {value:{propA:'testA',propB:'testB'}};
Object.defineProperty(obj.value,'propA',{
get: function(){return this.value;},
set: function(newValue){this.value=newValue;console.log('propA: ',newValue);}
});
console.log(obj.value.propA);
obj.value.propA = 'testA';
Object.defineProperty(obj.value,'propB',{
get: function(){return this.value;},
set: function(newValue){this.value=newValue;console.log('propB: ',newValue);}
});
console.log(obj.value.propB);
obj.value.propB = 'testB';
console.log('propA: ',obj.value.propA,' --propB: ',obj.value.propB);
the getter assigns the value to ALL the properties set by defineProperty within the object.
If this is the correct functionality, is there a way to have the getter/setter work only on the property defined such that in the fiddle above, propA would yield testA and propB would yield testB?
The getter and setter only apply to the named property, but this inside each one refers to the object whose property it is (you don’t have to have a backing variable for every property).
In your example, you’re always reading and modifying obj.value.value. You can create a different variable for each one by wrapping each in an IIFE, for example:
(function () {
var value;
Object.defineProperty(obj.value, 'propA', {
get: function () { return value; },
set: function (newValue) { value = newValue; },
});
})();
Updated fiddle
As you can see in the example below, I'm trying to wrap every function defined in obj so it gets to be able to be called with anotherObj as this, and then add that wrapper as a property to anotherObj.
Note: isFunction
var isFunction = function(x) {
return typeof(x) == "function";
}
for (prop in obj) {
if (isFunction(obj[prop])) {
var fn = obj[prop];
anotherObj[prop] = function() {
fn.call(anotherObj);
};
}
}
For some reason weird to me, every property now stored in anotherObj, references only the last property of the iteration.
However, if I use an external function like below, the references are ok.
var contextFn = function(fn, context){
return function() {
fn.call(context);
};
};
...
for (prop in obj) {
...
anotherObj[prop] = contextFn(fn, anotherObj);
...
}
Why is this happening? Is there something obvious I'm missing?
The (not-so-)obvious thing you're missing is that in your first loop, the variable "fn" is not local to the statement block it's declared in. Thus, it's shared by all the functions you're creating.
Your solution is in fact the correct one. By using a separate function, you're making copies of the values to be used in creating the actual wrapper functions, so that each wrapper will have it's own private copy of "fn".
Say I have a class and some static helper methods like this:
function MyClass (myVar) {
this.myVar = myVar;
this.replaceMe = function (value) {
// this will fail
this = MyClass.staticHelper( value );
return this;
}
this.revealVar = function () {
alert( this.myVar );
}
}
MyClass.staticHelper = function (instance, value) {
return new MyClass( instance.myVar + value );
}
What I want to do is something like this:
var instance = new MyClass( 2 );
instance.revealVar(); // alerts 2
instance.replaceMe( 40 ).revealVar(); // alerts 42
The reason is that my class has a slightly more complicated structure and I don't want to assign all internal variables manually everytime, but rather replace the entire object. Is there a simple way to do so?
instance.replaceMe( 40 ).revealVar(); alerts 42
OK, for that return MyClass.staticHelper(this, value); would suffice. The question is only whether the next call to instance.revealVar() should now alert 2 or 42 - if you want instance to be changed to 42 it gets more complicated:
this = MyClass.staticHelper( value ); // this will fail
…because this is not a common variable, but a keyword and evaluates to the value of the ThisBinding of the current execution context which is set depending on how the function is entered - you cannot assign to it, you can only set it when invoking the function.
I don't want to assign all internal variables manually everytime, but rather replace the entire object.
Unfortunately you have to do so, without changing the properties of instance object (and the closure-hidden variables) you won't change the instance and revealVar() will stay 2.
Is there a simple way to do so?
Yes, it can be done programmatically. The simplest method would be to call the constructor (again) on the current instance, like it happens when invoked with the new keyword:
MyClass.call( instance, instance.myVar + value );
Yet you can't use this like the static function which creates a completely new instance. Either you put it in a static method and call that from replaceMe with this, or you just put it directly in replaceMe.
If you need a static method that at first returns a completely new instance, you could use that as well by copying the new properties on the old instance:
….replaceMe = function(val) {
var newInst = MyClass.staticHelper(this, val); // new MyClass(this.myVar+val);
for (var prop in newInst)
if (newInst.hasOwnProperty(prop))
this[prop] = newInst[prop];
return this;
};
That means overwriting the old attributes, and also the old closures can be garbage-collected now as nothing refers to them any more.
Btw, I'd recommend to put your methods on the prototype instead of assigning them in the constructor.
How about just returning the new instance:
function MyClass(myVar) {
// ...
this.replaceMe = function (value) {
return MyClass.staticHelper(this, value);
}
// ...
}
MyClass.staticHelper = function (instance, value) {
return new MyClass( instance.myVar += value );
}
There are two reasons why this is not going to work in Javascript.
First, despite that it looks like a variable, this is actually a function call* and therefore cannot be assigned to. this=foo is the same as bar()=baz. So it's not possible to have code like this:
a = 5
a.change(10)
alert(a == 10) // nope
Second, even if this=z were possible, that approach would fail anyways, because Javascript passes by value, therefore it's not possible to have a function that changes the value of its argument:
a = 5
change(a)
alert(a == 10) // nope
* "is" means "fully identical in every way"
I wanted to do something very similar a while back. Unfortunately there's no way to assign a value to this - the this pointer is a read only variable. However the next best thing is to use a getter and setter object to change the variable holding your instance itself.
Note that this only updates a single reference to the instance. You can read more about it here: Is there a better way to simulate pointers in JavaScript?
So this is how it works:
function MyClass(pointer, myVar) {
this.myVar = myVar;
this.replaceMe = function (value) {
pointer.value = MyClass.staticHelper(this, pointer, value);
return pointer.value;
};
this.revealVar = function () {
alert(this.myVar);
};
}
MyClass.staticHelper = function (instance, pointer, value) {
return new MyClass(pointer, instance.myVar + value);
};
This is how to create the pointer and use it:
var instance = new MyClass({
get value() { return instance; },
set value(newValue) { instance = newValue; }
}, 2);
instance.revealVar(); // alerts 2
instance.replaceMe(40).revealVar(); // alerts 42
It's not the most elegant solution but it gets the job done. You can see this code in action: http://jsfiddle.net/fpxXL/1/
Does anyone have any example implementation of making individual object props readOnly/non-configurable? I mean primitive data types. Have tried using ES5 Object API, but hitting a brick wall.
I can't show code, because it's still at that "messy" phase, but basically I'm iterating through an outside object which, itself, holds numeruos objects. Those objects each hold various primitive data types. I have made the outer objects readOnly, non-config, etc, but can't figure out how to do likewise for individual props, the innermost props.
So, if outer.inner.prop === "Hello", I want to make that value readOnly.
Thanks!
UPDATE
I just figured this out, it was all in the for loop I was using to iterate over props. Now I've actually get data descriptors for the props, even the primitive ones. :) Thanks all!
You have to iterate through the inner object, since there is no way to deep-freeze an object using standard ES5 methods.
function deepFreeze(obj) {
Object.keys(obj).forEach(function (key) {
if (typeof obj[key] == 'object')
deepFreeze(obj[key]);
});
Object.freeze(obj);
}
Edit:
Also works for defineProperty if you don't want to freeze:
function deepWriteProtect(obj) {
Object.keys(obj).forEach(function (key) {
if (typeof obj[key] == 'object')
deepWriteProtect(obj[key]);
Object.defineProperty(obj, key, { writable: false });
});
}
I'm not 100% sure I understand your question correctly, but from what I gather you are asking for private variables. If so, that can be easily achieved using closures.
function myClass(){
var mySecretProperty = 10;
this.getMySecretProperty = function(){
return mySecretProperty;
}
this.changeMySecretProperty = function(s){
// whatever logic you need for a setter method
mySecretProperty = s;
}
}
var myObj = new MyClass();
myObj.changeMySecretProperty(120);
myObj.getMySecretProperty(); // will return 120
myObj.mySecretProperty // will return undefined
Would the following (ES5) example help? It creates an empty constructor, with a getter for property a (and no setter, so de facto a is read only):
var Obj = function(){};
Obj.prototype = {
get a() {return 5;}
}
var x = new Obj;
alert(x.a); //=> 5
x.a = 6; //=> TypeError: setting a property that has only a getter
Not using ES5 you can do
var Obj = function(){
var a = 5;
if (!Obj.prototype.getA) {
Obj.prototype.getA = {
toString: function() {
return a;
}
};
}
}
var y = new Obj;
alert(y.getA); //=> 5
But that is not 100% failsafe: Obj.prototype.getA can be overwritten.
Here is a jsfiddle showing how you can use ES5 getter/setter definitions to make a property of an object something that can only be fetched. The code looks like this:
var object = {
get x() {
return 17;
}, set x() {
alert("You cannot set x!");
}
};
Of course the getter could obtain the value of the property ("x") from anywhere, like a closure from a constructor or something. The point is that the setter simply does not change the value, so attempts to change it:
object.x = 100;
will not have any effect.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
detect variable change in javascript
How can i found out that my variable has changed?
I have an event that performed every time when my variable is for example == 1, i want it to perfome only when my variable changes.
You can do that via a property setter, which is a newly-standardized part of the language (new as of the ECMAScript5 specification). That will only work for a property defined with a setter on an object, not with any old variable or property.
Here's an example of an object with a foo property with both a getter and a setter:
var obj = {};
Object.defineProperty(obj, "foo", (function(){
var value = 42;
function fooGet() {
display("Getting: " + value);
return value;
}
function fooSet(newValue) {
display("Setting: " + newValue);
value = newValue;
}
return {
get: fooGet,
set: fooSet
};
})());
Live example, but only works on browsers with support for ECMAScript5 properties, which I think is just Google Chrome at the moment
Or of course, just directly use getter and setter functions rather than properties. :-)
Simple: Don't use a primitive variable but an object which has a "setter" method to change the value. In the setter, you can call additional code.
You can't do this with primitives. The only way it would be possible is if you encapsulated the variable in an object, and added some custom events to this object.
#T.J. I think #Aaron is suggesting an object that does something like this:
var myVar = new Watched(1, function (newValue) { alert(newValue) });
myVar.add(2); // alert(3);
myVar.add(10); // alert(13)
Where Watched maintains an internal value that is updated by methods, which fire a callback to say they have updated.
EDITED:
Ok maybe not what #Aaron was thinking:)
I had something very simple like this in mind:
function Watched (initVal, cb) {
var value = initVal;
function add (val) {
value += val;
cb(value);
}
// return public methods
return { add: add };
}
You could use the setInterval method to periodically check the variable's value and do your stuff if it's what you want.
It's not a nice solution, though. The other suggestions are better.
http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/
EDIT:
var myVar = 0;
var intervalId = setInterval('checkVariable(myVar);', 3000);
function checkVariable(theVar) {
if (theVar == 1) {
alert('Variable is 1.');
}
}
That will execute checkVariable(myVar) every 3 seconds.