李壮志 发表于 2023-5-26 22:45:52

深入理解 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 = ;
//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.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);//993.apply链接构造器用法
你可以使用 apply 来链接一个对象构造器,类似于 Java。(Java的对象构造器用来创建对象,也可以对对象属性做一些特殊处理,如时间格式化)
在接下来的例子中我们会创建一个全局 Global_Objects/Function 对象的 construct 方法,来使你能够在构造器中使用一个类数组对象而非参数列表。
个人理解:给全局的Function 类定义一个construct方法,并且在construct方法中根据现有对象创建一个新的对象,利用apply链接构造器,返回一个新的对象,此时对全局的Function 对象拥有了一个的 construct 方法,能够返回类数组对象
<strong>注意,这个construct方法是新定义的,不是原本的constructor</strong><em id="__mceDel"><strong><strong>定义中描述的类数组对象是下图的样子:</strong></strong></em>
//给全局的Function 类定义一个construct方法,并且在construct方法中创建一个新的对象,利用apply链接构造器,返回一个新的对象Function.prototype.construct = function (aArgs) {<br>  //Object.create() 静态方法以一个现有对象作为原型,创建一个新对象let oNew = Object.create(this.prototype);
this.apply(oNew, aArgs);
return oNew;
};

function MyConstructor() {<br>  //这里就是对数组进行遍历,然后封装成k:v的形式
for (let nProp = 0; nProp < arguments.length; nProp++) {
    this["property" + nProp] = arguments;
}
}
//定义一个数组
let myArray = ["zooey", "Hello world!", "anan"];

let myInstance = MyConstructor.construct(myArray);
//打印结果
console.log(myInstance); 

来源:https://www.cnblogs.com/zry123/p/17435074.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!
页: [1]
查看完整版本: 深入理解 apply()方法