1

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.

2
  • this.defaults.purpose.my_variable is one of them Commented Sep 16, 2013 at 12:34
  • this.defaults.purpose.my_variable would work as long as you continue to call the function the way you currently do. Commented Sep 16, 2013 at 12:34

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

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.
Did you intend this answer as a joke? (I'm not sure whether to provide serious feedback or not.)
Oh great, thanks. there can be also use .call(this.defaults.purpose);
2

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.