I have this example code:
var foo = {
self: this,
init: function(){
self.doStuff();
},
doStuff: function(){
alert('doing stuff');
}
}
foo.init();
Why the refence "self" doesn't work?
Thanks!
Objects are assigned and copied by reference. In other words, a variable stores not the “object value”, but a “reference” (address in memory) for the value. So copying such a variable or passing it as a function argument copies that reference, not the object itself.
Every object can access a reference to itself with keyword this (sometimes called the this reference). When an instance method is called for a particular object, the method's body implicitly uses keyword this to refer to the object's instance variables and other methods.
Unfortunately, JSON doesn't support recursion/self-referencing. This isn't JSON. Are you asking about self-references while creating an object using literal syntax? Or are you saying that you want the specified values to update automatically with changes to the referenced values?
The Object literal notation is basically an array of key:value pairs, with a colon separating the keys and values, and a comma after every key:value pair, except for the last, just like a regular array. Values created with anonymous functions are methods of your object. Simple values are properties.
Because at the time you declare the object literal this
is not a reference to the object, but to whatever the calling context is.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With