假设我有一个对象'msg',我在以下情况下重新定义它,但我不了解它的属性的行为(特别是 m1)。为什么它在对象内部未定义并且当我通过函数访问它时它给出字符串值(最后一种情况)。你能解释每种情况吗
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)