2023年3月27日 星期一

JavaScript 匿名函式作為物件方法的回傳值範例


在 JavaScript 中,匿名函式作為物件方法的回傳值時,其 this 可能會指向全域物件。以下是範例程式碼:

<script type="text/javascript">
var name = "Tom"; // 宣告全域變數 name,賦予初值字串 "Tom"

var Object_B = { // 使用物件實字建立 Object_B
name: "Jack",
};

var Object_A = { // 使用物件實字建立 Object_A
name: "John" ,
test_1: function(){
return function(){this.name = "Mary"; };
},
};

console.log(this.name); // Tom
console.log(Object_A.name); // John

var t_run = Object_A.test_1(); // 呼叫物件 Object_A 的 test_1 方法,將回傳的匿名函式賦值給 t_run

t_run(); // 呼叫 t_run 結果將全域變數 name 改為 "Mary"

console.log(this.name); // Mary (原本是 Tom)
console.log(Object_A.name); // John

/* 修正 this 指向問題 
當匿名函式回傳時,this 指向全域物件。若希望 this 指向物件本身 ( 例如 Object_A ),可以使用 .bind(this) 方法來綁定 this 。
*/

var  name = "Tom";
var Object_B = {
name: "Jack",
};
var Object_A = {
name: "John",
test_1: function(){
return function(){ this.name = "Mary"; }.bind(this); // 使用 bind(this) 將this 綁定為 Object_A
},
};
var t_run = Object_A.test_1();
t_run(); // 呼叫 t_run 後,Object_A 的 name 會被改為 "Mary"

console.log(this.name); // Tom
console.log(Object_A.name); // Mary (John 變成 Mary).

</script>

結論:
當匿名函式作為物件方法的回傳值時,若沒有特別處理,this 將指向全域物件。要讓 this 指向所屬的物件 ( 例如 Object_A ),可以使用 .bind(this) 方法來綁定 this。

沒有留言:

張貼留言

請注意 : 您的留言發佈成功 , 需經審核後 , 才能決定是否回覆 . 謝謝 !!