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.
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.
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
}