訊息稱 EDA 軟體商新思科技正被美國商務部調查,涉嫌轉讓關鍵技術給華為海思、中芯國際
阿新 • • 發佈:2022-04-15
JavaScript 中 call()、apply()、 bind()的用法
var name="cristiano.Zhao" var info = { name:"cris", objAge: this.age, myFunc: function(){ console.log(this.name + "年齡" + this.age); } }
列印結果
info.objAge; //27 obj.myFunc() // cris name undefind
分析:在 console 列印中,this 指向 info, 因此,name打印出 cris, 而 age 列印 undefind.
call()、apply()、bind() 都是用來重定義 this 這個物件的!
var name="Georgina ",age=27; var other={ name:"cristiano.Zhao", objAge:this.age, myFunc:function(){ console.log(this.name + "年齡" + this.age); } } var example = { name:"cris", age:"27" } obj.myFunc.call(example); // cris 27obj.myFunc.apply(example); // cris 27 obj.myFunc.bind(example)(); // cris 27
三個函式引數結構中,第一個引數都是指向 this 物件,
1、對 call 來講,引數直接傳遞,例如 obj.myFunc(example, "male", "front-end");
2、對 apply 來講,所有引數都必須放在一個數組裡面傳進去, 例如 obj.myFunc.apply(example, ["male", "front-end"]);
3、對 bind 來講,引數傳遞與 call 相同,但是返回一個函式,因此要立即執行之後,才能正確執行;