apply(thisArg)
apply(thisArg, argsArray)
thisArg
在 func 函式運行時使用的 this 值,請注意,this 可能不是該方法看到的實際值:如果這個函式處于非嚴格模式下,則指定為 null 或 undefined 時會自動替換為指向全域物件,原始值會被包裝,
argsArray 可選
一個陣列或者類陣列物件,其中的陣列元素將作為單獨的引數傳給 func 函式,如果該引數的值為 null 或 undefined,則表示不需要傳入任何引數,從 ECMAScript 5 開始可以使用類陣列物件,瀏覽器兼容性請參閱本文底部內容,
回傳值
呼叫有指定 this 值和引數的函式的結果,
1.陣列合并用法
const arr1 = ["anan", "zooey"]; const arr2 = [198, 246, 357]; //1.1 apply() arr1.push.apply(arr1, arr2); // console.log(arr1);//['anan','zooey',198,246,357] //1.2call() arr1.push.call(arr1, ...arr2); // console.log(arr1);//['anan','zooey',198,246,357] //1.3 es6 const newArr = [...arr1, ...arr2]; // console.log(newArr);//['anan','zooey',198,246,357]
2.內置函式用法
const num = [2, 5, 3, 6, 9, 0, 99]; //2.1 錯誤用法 let max1 = Math.max(num); // console.log(max1);//NaN //2.2 apply() let max2 = Math.max.apply(null, num); // console.log(max2);//99 //2.3 es6 let max3 = Math.max(...num); // console.log(max3);//99 //2.4 call() let max4 = Math.max.call(null, ...num); // console.log(max4);//99
3.apply鏈接構造器用法
你可以使用 apply 來鏈接一個物件構造器,類似于 Java,(Java的物件構造器用來創建物件,也可以對物件屬性做一些特殊處理,如時間格式化)
在接下來的例子中我們會創建一個全域 Global_Objects/Function 物件的 construct 方法,來使你能夠在構造器中使用一個類陣列物件而非引數串列,
個人理解:給全域的Function 類定義一個construct方法,并且在construct方法中根據現有物件創建一個新的物件,利用apply鏈接構造器,回傳一個新的物件,此時對全域的Function 物件擁有了一個的 construct 方法,能夠回傳類陣列物件
注意,這個construct方法是新定義的,不是原本的constructor
定義中描述的類陣列物件是下圖的樣子:

//給全域的Function 類定義一個construct方法,并且在construct方法中創建一個新的物件,利用apply鏈接構造器,回傳一個新的物件
Function.prototype.construct = function (aArgs) {//Object.create() 靜態方法以一個現有物件作為原型,創建一個新物件
let oNew = Object.create(this.prototype); this.apply(oNew, aArgs); return oNew; }; function MyConstructor() {
//這里就是對陣列進行遍歷,然后封裝成k:v的形式 for (let nProp = 0; nProp < arguments.length; nProp++) { this["property" + nProp] = arguments[nProp]; } } //定義一個陣列 let myArray = ["zooey", "Hello world!", "anan"]; let myInstance = MyConstructor.construct(myArray); //列印結果 console.log(myInstance);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/553545.html
標籤:其他
上一篇:記錄--前端小票列印、網頁列印
下一篇:返回列表
