JavaScript之a(chǎn)pply()與call()細(xì)談

Function也是一種對象,有自己的屬性和方法。call和apply就是js函數(shù)自帶方法,掛在Fucntion.prototype上。一般調(diào)用某函數(shù)時,直接“函數(shù)名(參數(shù))”的寫法即可,函數(shù)內(nèi)部的this指向函數(shù)的調(diào)用者。call和apply的作用是給函數(shù)重新指定調(diào)用者,指定this的指向:

Javascript 的 this 用法

函數(shù)的不同使用場合,this有不同的值??偟膩碚f,this就是函數(shù)運(yùn)行時所在的環(huán)境對象。下面分四種情況,詳細(xì)討論this的用法。

  1. 純粹的函數(shù)調(diào)用
var x = 1;
function test() {
   console.log(this.x);
}
test();  // 1
  1. 作為對象方法的調(diào)用
    函數(shù)還可以作為某個對象的方法調(diào)用,這時this就指這個上級對象。
function test() {
  console.log(this.x);
}

var obj = {
    x: 1,
    m: test
};
obj.m(); // 1
  1. 作為構(gòu)造函數(shù)調(diào)用
    所謂構(gòu)造函數(shù),就是通過這個函數(shù),可以生成一個新對象。這時,this就指這個新對象。
function test() {
 this.x = 1;
}
var obj = new test();
obj.x // 1

var x = 2;
function test() {
  this.x = 1;
}
var obj = new test();
x  // 2
  1. apply 、call調(diào)用
    apply()、call()是函數(shù)的一個方法,作用是改變函數(shù)的調(diào)用對象。它的第一個參數(shù)就表示改變后的調(diào)用這個函數(shù)的對象。因此,這時this指的就是這第一個參數(shù)。
var x = 0;
function test() {
 console.log(this.x);
}
var obj = {};
obj.x = 1;
obj.m = test;
obj.m.apply() // 0
obj.m.apply(obj); //1

apply()的參數(shù)為空時,默認(rèn)調(diào)用全局對象。因此,這時的運(yùn)行結(jié)果為0,證明this指的是全局對象;call()同理

call()與apply()詳解

  let obj = {name: 'tony'};
  
  function Child(name){
    this.name = name;
  }
  
  Child.prototype = {
    constructor: Child,
    showName: function(){
      console.log(this.name);
    }
  }
  var child = new Child('thomas');
  child.showName(); // thomas
  
  //  call,apply,bind使用
  child.showName.call(obj); // tony
  child.showName.apply(obj); // tony
  let bind = child.showName.bind(obj); // 返回一個函數(shù)
  bind(); // tony

定義:
apply:調(diào)用一個對象的一個方法,用另一個對象替換當(dāng)前對象。例如:B.apply(A, arguments);即A對象應(yīng)用B對象的方法。

call:調(diào)用一個對象的一個方法,用另一個對象替換當(dāng)前對象。例如:B.call(A, args1,args2);即A對象調(diào)用B對象的方法。

共同點:
都“可以用來代替另一個對象調(diào)用一個方法,將一個函數(shù)的對象上下文從初始的上下文改變?yōu)橛蓆hisObj指定的新對象”。改變函數(shù)執(zhí)行時的上下文,再具體一點就是改變函數(shù)運(yùn)行時的this指向。

不同點:
實際上,apply和call的功能是一樣的,只是傳入的參數(shù)列表形式不同。

let arr1 = [1, 2, 19, 6];
//例子:求數(shù)組中的最值
console.log(Math.max.call(null, 1,2,19,6)); // 19
console.log(Math.max.call(null, arr1)); // NaN
console.log(Math.max.apply(null, arr1)); //  19 直接可以用arr1傳遞進(jìn)去

bind: bind方法是事先把fn的this改變?yōu)槲覀円胍慕Y(jié)果,并且把對應(yīng)的參數(shù)值準(zhǔn)備好,以后要用到了,直接的執(zhí)行即可,也就是說bind同樣可以改變this的指向,但和apply、call不同就是不會馬上的執(zhí)行

例子

function fn() {
    console.log(this);
}
// apply方法結(jié)果同下
fn.call(); // 普通模式下this是window,在嚴(yán)格模式下this是undefined
fn.call(null); // 普通模式下this是window,在嚴(yán)格模式下this是null
fn.call(undefined); // 普通模式下this是window,在嚴(yán)格模式下this是undefined

應(yīng)用

使用apply和內(nèi)置函數(shù)
用Math.max/Math.min求得數(shù)組中的最大/小值

/* 找出數(shù)組中最大/小的數(shù)字 */
let numbers = [5, 6, 2, 3, 7];

/* 使用Math.min/Math.max以及apply 函數(shù)時的代碼 */
let max = Math.max.apply(null, numbers); /* 基本等同于 Math.max(numbers[0], ...) 或 Math.max(5, 6, ..) */
let min = Math.min.apply(null, numbers);

/* 對比:簡單循環(huán)算法 */
max = -Infinity, min = +Infinity;

for (var i = 0; i < numbers.length; i++) {
  if (numbers[i] > max)
    max = numbers[i];
  if (numbers[i] < min)
    min = numbers[i];
}

數(shù)組拼接,添加

let arr1 = [1,2,3];
let arr2 = [4,5,6];

//數(shù)組的concat方法:返回一個新的數(shù)組
let arr3 = arr1.concat(arr2); 
console.log(arr3); // [1, 2, 3, 4, 5, 6]

console.log(arr1); // [1, 2, 3] 不變
console.log(arr2); // [4, 5, 6] 不變
// 用 apply方法
[].push.apply(arr1,arr2);  // 給arr1添加arr2
console.log(arr1); // [1, 2, 3, 4, 5, 6]
console.log(arr2); // 不變

判斷變量類型

let arr1 = [1,2,3];
let str1 = 'string';
let obj1 = {name: 'thomas'};
//
function isArray(obj) {
  return Object.prototype.toString.call(obj) === '[object Array]';
}
console.log(isArray(arr1)); // true

//  判斷類型的方式,這個最常用語判斷array和object,null(因為typeof null等于object)  
console.log(Object.prototype.toString.call(arr1)); // [object Array]
console.log(Object.prototype.toString.call(str1)); // [object String]
console.log(Object.prototype.toString.call(obj1)); // [object Object]
console.log(Object.prototype.toString.call(null)); // [object Null]

利用call和apply做繼承

function Animal(name){      
    this.name = name;      
    this.showName = function(){      
        console.log(this.name);      
    }      
}      

function Cat(name){    
    Animal.call(this, name);    
}      

// Animal.call(this) 的意思就是使用this對象代替Animal對象,那么
// Cat中不就有Animal的所有屬性和方法了嗎,Cat對象就能夠直接調(diào)用Animal的方法以及屬性了
var cat = new Cat("TONY");     
cat.showName();   //TONY

多繼承

  function Class1(a,b) {
    this.showclass1 = function(a,b) {
      console.log(`class1: ${a},$`);
    }
  }

  function Class2(a,b) {
    this.showclass2 = function(a,b) {
      console.log(`class2: ${a},$`);
    }
  }

  function Class3(a,b,c) {
    Class1.call(this);
    Class2.call(this);
  }

  let arr10 = [2,2];
  let demo = new Class3();
  demo.showclass1.call(this,1); // class1: 1,undefined
  demo.showclass1.call(this,1,2); // class1: 1,2
  demo.showclass2.apply(this,arr10); // class2: 2,2

總結(jié)

apply()與call()在日常編碼中使用的頻率不是很高,但對于我們學(xué)習(xí)JavaScript是非常重要的一節(jié)。

作者V: codejs

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容