1

假设我有一个对象'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) 
4

1 回答 1

3

this永远不会通过对象文字语法引用当前正在生成的对象。

this指环境的调用上下文。对象本身没有调用上下文,但它们可以用作调用上下文。

注意你的msg4.m2()作品。这是因为this是函数的调用上下文,以及对调用方法的对象的引用,也就是msg4对象。

怎么msg4变成函数的调用上下文了m2?这是因为当你这样做时:

msg4.m2();

您正在调用m2 对象msg4。这会自动设置调用上下文,以便this指向msg4对象。

于 2012-09-27T17:52:30.867 回答