JavaScript Functions call()、apply()
一、call()
一個 javascript call() 的用法如下
var myObject = { firstName: "John", lastName: "Doe", fullName: function () { console.log(this.firstName + " " + this.lastName); } } var person1 = { firstName: "brian", lastName: "Bill" } myObject.fullName(); myObject.fullName.call(person1);
call() 的用途感覺就像是「用自己物件的處理方式,但屬性可以用別的物件輸入替換」。
call() 也可以代入 n 個參數,語法為 call(parameter1, parameter2, parameter3, n...)
var myObject = { firstName: "John", lastName: "Doe", fullName: function (country) { console.log(this.firstName + " " + this.lastName + " " + country); } }; var person1 = { firstName: "brian", lastName: "Bill" }; myObject.fullName.call(person1, "taiwan");
二、apply()
var myObject = { firstName: "John", lastName: "Doe", fullName: function (country, postcode) { console.log(this.firstName + " " + this.lastName + " " + country + " " + postcode); } }; var person1 = { firstName: "brian", lastName: "Bill" }; myObject.fullName.apply(person1, ["taiwan", 666]);
說明:
1、call() 與 apply() 的差異在於參數代入的型式,apply() 可以接受所有要傳的參數打包成陣列送入。
2、如果不需代參數進去的話,call() 跟 apply() 的效果是一樣的。
var myObject = { firstName: "John", lastName: "Doe", fullName: function () { console.log(this.firstName + " " + this.lastName); } } var person1 = { firstName: "brian", lastName: "Bill" } myObject.fullName(); myObject.fullName.apply(person1);