Search code examples
javascriptjqueryvariablesplugins

Refer to options within variables in jQuery


Just curious about jQuery/Javascript and referring to options within variables.

So, I wrote a little plugin that when I call "populate" will fill in some text. Very basic. Here's what I'm trying to do:

var foo = {
    msg1: "Hey",
    msg2: this.msg1 + "how",
    msg3: this.msg2 + "are",
    msg4: this.msg3 + "you",
    msg5: this.msg4 + "doing",
    msg6: this.msg5 + "today"
}

$("#bar").populate({text: foo.msg6});

So when the .populate plugin is called, #bar will get "Hey how are you doing today" added to it.

The populate plugin is hard to explain but trust me it's working great and not the issue. I'm just curious if this sort of organization of variables and options is possible, as it seems cleaner, more "semantic", and more organized to me than just a bunch of variables referring to other variables...


Solution

  • this only has meaning in an execution context. When you define a function, a scope chain is created for that function that will be used whenever that function enters the current execution context. When that occurs, this will become defined (at runtime). See this for more details.

    In your example, you are not defining any new scope chains, because you are not creating any methods on your object. Therefore, when you refer to this, you are referring to whatever this is whenever you make your foo object. Most likely, you are working in the global space, so this will be window (if you're in the browser), but it could be another object that has a function that you are currently executing in. For example:

        var myScopeObj = {
            myMethod: function() {
                var foo = {
                    msg1: "Hey",
                    msg2: this.msg1 + "how",
                    msg3: this.msg2 + "are",
                    msg4: this.msg3 + "you",
                    msg5: this.msg4 + "doing",
                    msg6: this.msg5 + "today"
                };
                var foo2 = foo.msg6;
            }
        };
    

    There are a couple of possibilities in the above example:

        myScopeObj.myMethod();  // 'this' refers to myScopeObj
    

    or

        var method = myScopeObj.myMethod;
        method();  // 'this' refers to window
    

    or

        myScopeObj.myMethod.call(window);  // 'this' refers to window
    

    What you could do is use make a constructor function for your object, and use this to map properties.

        function Foo() {
            this.msg1 = "Hey";
            this.msg2 = this.msg1 + "how";
            this.msg3 = this.msg2 + "are";
            this.msg4 = this.msg3 + "you";
            this.msg5 = this.msg4 + "doing";
            this.msg6 = this.msg5 + "today";
        };
        var foo = new Foo();
        $("#bar").populate({text: foo.msg6});