I have following script
<script>
var Obj = {
purpose_1: {
defaults: {
purpose:{ my_variable:"Test" }
},
activity: function() {
console.log( Obj.purpose_1.defaults.purpose.my_variable );
}
},
purpose_2: {
}
}
Obj.purpose_1.activity();
</script>
I am accessing my_variable and getting output Test in console from line
console.log( Obj.purpose_1.defaults.purpose.my_variable );
Is there any short cut way like
this.my_variable
to access my_variable instead of this long path
Obj.purpose_1.defaults.purpose.my_variable
Thanks.
asked Sep 16, 2013 at 12:30
MD SHAHIDUL ISLAM
14.5k6 gold badges84 silver badges93 bronze badges
2 Answers 2
activity: function () {
return function() {
//this now refers to Obj.purpose_1.defaults.purpose
console.log(this.my_variable);
}.call(Obj.purpose_1.defaults.purpose);
// call overrides the context in which the function is executed
}
Return a function bound to the context you need! Here is a sample fiddle.
See the Function.prototype.call method at MDN.
answered Sep 16, 2013 at 12:43
Niccolò Campolungo
12k4 gold badges36 silver badges40 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
BlitZ
Made own sandbox... Well, nice (: +1 But do not forget to save reference to current context:
var self = this before return function(){ ... }.call() will give direct access to both objects.nnnnnn
Did you intend this answer as a joke? (I'm not sure whether to provide serious feedback or not.)
MD SHAHIDUL ISLAM
Oh great, thanks. there can be also use .call(this.defaults.purpose);
Because of javascript objects are implicitly passing by reference, you may create shortcuts for yourself like this:
activity: function() {
var p = this.defaults.purpose; // shortcut
console.log(p.my_variable); // property
}
answered Sep 16, 2013 at 12:38
BlitZ
12.2k3 gold badges52 silver badges70 bronze badges
Comments
default
this.defaults.purpose.my_variableis one of themthis.defaults.purpose.my_variablewould work as long as you continue to call the function the way you currently do.