let consider i have a object ‘msg’ i re-define it in following cases but i am not understand the behaviour of its property (specially m1). why it is undefined inside the object and it is give string value when i access it through function (last case). can you explain for each case
case 0
var msg = {
m1 : "this is string",
m2 : "ok, " + this.m1
};
console.log(msg.m1); //this is string
console.log(msg.m2); // ok, undefined
/////// why m1 is undefined inside msg
//------------------------------------------
case 1
var msg1 = new Object(msg);
console.log(msg1.m1); //this is string
console.log(msg1.m2); // ok, undefined
//again undefined
//------------------------------------------
case 2
var msg2 = {
m1 : function () { return "this is string";},
m2 : "ok, " + this.m1,
m3 : typeof this.m1
};
console.log(msg2.m1()); //this is string
console.log(msg2.m2); // ok, undefined
console.log(msg2.m3); // undefined
console.log(typeof msg2.m1) // function 'but inside msg2 it is undefined why'
//------------------------------------------
case 3
var msg3 = {
m1 : (function () { return "this is string";}()),
m2 : "ok, " + this.m1,
m3 : typeof this.m1
};
console.log(msg3.m1); //this is string
console.log(msg3.m2); // ok, undefined
console.log(msg3.m3); // undefined
console.log(typeof msg3.m1) // string (atleast i know why this is ) but inside msg2 it is not defined (why )
//------------------------------------------
case 4
var msg4 = {
m1 : (function () { return "this is string";}()),
m2 : function () { return "ok, " + this.m1; },
m3 : typeof this.m1
};
console.log(msg4.m1); //this is string
console.log(msg4.m2()); // ok, this is string
console.log(msg4.m3); // undefined
console.log(typeof msg4.m1) // string (atleast i know why this is ) but inside msg2 it is not defined and in m2 it evaluated (why so)
thiswill never refer to the object that is currently being made via object literal syntax.thisrefers to the environment’s calling context. Objects themselves don’t have a calling context, but they can be used as a calling context.Notice your
msg4.m2()works. That’s becausethisis the calling context of the function, and a reference to the object on which the method was invoked, which is themsg4object.How did
msg4become the calling context of them2function? It’s because when you do this:you are invoking
m2on themsg4object. This automatically sets up the calling context so thatthispoints to themsg4object.