2014年5月30日 星期五

[js] this的討論

測試不使用chrome來測試了,改用node js!!

要使用瀏覽器測試直接調整global成window就可以。

var Method = function(str, obj){ console.log(str); console.log("\tthis:"+this); console.log("\tthis == global:"+(this == global)); console.log("\tthis == o:"+(this == o));
if(typeof obj != 'undefined'){
console.log("\tthis == obj:"+(this == obj));
}
if(this != global){
this.method = Method;
};
} var o = { method: Method };
// this == global Method("Method();");

// this == global
console.log("this == global:"+(this== global));

// this == o o.method("o.method();");


var inst = new Method("new Method();");
// this == obj => this == inst
inst.method("inst.method()", inst);

----

在這段程式的執行結果可以看到,直接呼叫method的時候,this是對應到全域的
global
另外全域的this也是

而o.method則是對應到物件本身

最後兩個則是確認new Method()確實會回傳一個新的物件 而且是this

沒有留言:

張貼留言