深入理解 apply()方法

2023/5/27 1:23:40

本文主要是介绍深入理解 apply()方法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

 

 

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);

 



这篇关于深入理解 apply()方法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程