在上一文《了解 .apply 和 .call 的區(qū)別》中,我們介紹了 .call
和 .apply
的有關知識,介紹了它們時如何工作的,并通過多個實例介紹了它們的區(qū)別。在本文中,將再通過多個示例,演示 .call
和 .apply
的使用區(qū)別。
語句
我們先看看 .call
和 .apply
的語句。
- .apply(this, [...])
- .call(this, param1, param2, param3, param4...)
可以看到,.apply
接受一個參數(shù)數(shù)組,而 .call
接受零個或多個單獨的參數(shù)。這是它們的句式區(qū)別。
apply()
方法與 call()
相同,只是 apply()
需要一個數(shù)組作為第二個參數(shù),該數(shù)組表示目標方法的參數(shù)。
所以:
- // 假設你有一個函數(shù) f
- function f(message) { ... }
- f.call(receiver, "test");
- f.apply(receiver, ["test"]);
.call
可不需要第一個參數(shù),但 .apply
第一個參數(shù)不可缺少。
示例一
這些方法對于賦予對象臨時功能非常有用。
- var friend = {
- car: false,
- lendCar: function ( canLend ){
- this.car = canLend;
- }
- };
- var me = {
- car: false,
- gotCar: function(){
- return this.car === true;
- }
- };
- console.log(me.gotCar()); // false
- friend.lendCar.call(me, true);
- console.log(me.gotCar()); // true
- friend.lendCar.apply(me, [false]);
- console.log(me.gotCar()); // false
示例二
- function Person(name) {
- this.name = name;
- }
- Person.prototype.getName = function(a,b) {
- return this.name + " " + a + " " + b;
- }
- var reader = new Person('John Smith');
- reader.getName = function() {
- // apply 和 call 執(zhí)行函數(shù)并返回值
- // 注意提取"getName"原型的不同方式
- var baseName = Object.getPrototypeOf(this).getName.apply(this,["is a", "boy"]);
- console.log("Apply: " + baseName);
- var baseName = Object.getPrototypeOf(reader).getName.call(this, "is a", "boy");
- console.log("Call: " + baseName);
- // bind 返回可以調用的函數(shù)
- var baseName = Person.prototype.getName.bind(this, "is a", "boy");
- console.log("Bind: " + baseName());
- }
- reader.getName();
- /* Output
- Apply: John Smith is a boy
- Call: John Smith is a boy
- Bind: John Smith is a boy
- */
示例三
- var obj1 = { which : "obj1" },
- obj2 = { which : "obj2" };
- function execute(arg1, arg2){
- console.log(this.which, arg1, arg2);
- }
- //使用 call
- execute.call(obj1, "dan", "stanhope");
- //output: obj1 dan stanhope
- //使用 apply
- execute.apply(obj2, ["dan", "stanhope"]);
- //output: obj2 dan stanhope
示例四
- let obj = {
- val1: 5,
- val2: 10
- }
- const summation = function (val3, val4) {
- return this.val1 + this.val2 + val3 + val4;
- }
- console.log(summation.apply(obj, [2 ,3])); //20
- // 首先,我們在第一個 arg 中分配 this 的值
- // 使用 apply 必須通過數(shù)組傳遞
- console.log(summation.call(obj, 2, 3)); //20
- // 使用 call 我們可以獨立地通過每個參數(shù)傳遞
實例五
- var car = {
- name: "Reno",
- country: "France",
- showBuyer: function(firstName, lastName) {
- console.log(`${firstName} ${lastName} just bought a ${this.name} from ${this.country}`);
- }
- }
- const firstName = "Bryan";
- const lastName = "Smith";
- car.showBuyer(firstName, lastName); // Bryan just bought a Reno from France
- const obj = { name: "Maserati", country: "Italy" };
- car.showBuyer.call(obj, firstName, lastName); // Bryan Smith just bought a Maserati from Italy
- car.showBuyer.apply(obj, [firstName, lastName]); // Bryan Smith just bought a Maserati from Italy
總結
本文通過5個示例,演示了jQuery .call 和 .apply 的使用區(qū)別。
相關文章