JavaScript中函數調用方式小結

新冠疫情的五一假期,沒有出去浪,在家把JS基礎溫故一下,小結一下目前我遇到的JS函數的調用方式。

可能有遺漏的,但是應該比較全了。

我進行了一下分類,一共分了約幾大類:

1,構造函數調用(2種)

2,直接調用(1種)

3,通過call, apply等方式調用(4種)

4,通過bind調用(1種)

5,自執行函數直接調用(嚴格上說,不算一種調用方式),這個不舉例了

老樣子,直接擼代碼:

/**
 * 這是一個綜合應用的練習文件,總結和練習JS中函數調用的一些方式
 * @data 2020.05.05  15:30
 * @author [email protected]
 * 
 */

 function Person(name,age, callType) {
     console.log(`Person :: enter, name = ${name}, age = ${age}, callType = [${callType}]`);    
    this.name = name;
    this.age = age;
 }

 // 1 構造函數的方式(2種):
 let pConstructor1 = new Person("迪麗熱巴", 20, "new Constructor");
 let pConstructor2 = Reflect.construct(Person,["楊超越", 19, "Reflect.construct"]);

 // 2, 直接調用(1種)
 Person("劉詩詩", 19, "normal");

 // 3, call
 Person.call(null, ...["楊冪", 19, "Person.call"]); // 注意是參數列表,需要展開一下

 // 4, apply
 Person.apply(null, ["湯唯", 20, "Person.apply"]); // 注意參數列表,不需要展開

 // 5, 藉助函數的基類方法apply, 過於冗繁了。。。
 Function.prototype.apply.call(Person, null, ["古靈精怪", 17, "Function.prototype.apply.call"]); // 注意參數哈
 
 // 6, Reflect.apply
 Reflect.apply(Person,null,["劉亦菲", 16 , " Reflect.apply"]);

 // 7, bind後調用
 let newFunc = Person.bind(null, ...["宋慧喬", 21 , " bind "]); // 不直接調用,注意跟call apply的區別
 console.log(`bind Person end`);
 newFunc("不管用",16, "bind後調用"); // 參數已經被緩存了
 newFunc()

 // 以上代碼的輸出內容:
// Person :: enter, name = 迪麗熱巴, age = 20, callType = [new Constructor]
// Person :: enter, name = 楊超越, age = 19, callType = [Reflect.construct]
// Person :: enter, name = 劉詩詩, age = 19, callType = [normal]
// Person :: enter, name = 楊冪, age = 19, callType = [Person.call]
// Person :: enter, name = 湯唯, age = 20, callType = [Person.apply]
// Person :: enter, name = 古靈精怪, age = 17, callType = [Function.prototype.apply.call]
// Person :: enter, name = 劉亦菲, age = 16, callType = [ Reflect.apply]
// bind Person end
// Person :: enter, name = 宋慧喬, age = 21, callType = [ bind ]
// Person :: enter, name = 宋慧喬, age = 21, callType = [ bind ]
 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章