this only makes sense in the execution context . When you define a function, a scope chain is created for this function, which will be used whenever this function enters the current execution context. When this happens, this will be determined (at runtime). See more details.
In your example, you are not defining any new scope chains because you are not creating any methods for your object. Therefore, when you refer to this , you refer to all this when you make your foo object. Most likely, you work in a global space, so this will be window (if you are in a browser), but it may be another object with a function in which you are currently executing. For instance:
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 several 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 can do is use the 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});
source share