为了能到远方,脚下的每一步都不能少.|

lmyyyy

园龄:2年8个月粉丝:7关注:10

5月22日总结

深入理解 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方法是新定义的,不是原本的constructo

本文作者:lmyyyy

本文链接:https://www.cnblogs.com/lmyy/p/17435405.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   lmyyyy  阅读(5)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起