apply(thisArg)

apply(thisArg, argsArray)

thisArg

func函数运行时使用的this值。请注意,this可能不是该方法看到的实际值:如果这个函数处于非严格模式下,则指定为nullundefined时会自动替换为指向全局对象,原始值会被包装。

argsArray可选

一个数组或者类数组对象,其中的数组元素将作为单独的参数传给func函数。如果该参数的值为nullundefined,则表示不需要传入任何参数。从 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
定义中描述的类数组对象是下图的样子:

深入理解 apply()方法

//给全局的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);
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。