目录
1、概念
- 1、概念
- 2、MDN链接地址
- 3、代码
-
- 3.1、功能函数
- 3.2、被调用的函数
- 3.3、被指向的对象
- 3.4、函数调用
apply()方法调用一个具有给定 this 值的函数,以及以一个数组(或类数组对象)的形式提供的参数。
2、MDN链接地址MDN - apply
3、代码 3.1、功能函数Function.prototype.myapply = function(context = window, args) { // 如果this不是函数, // 抛出错误, // 退出程序。 if (typeof this !== "function") { throw new TypeError('not a function'); } else { // 否则把函数重新命名为fun, // 并且挂载到context对象上 // 也就是外面传进来的对象(applyData) context.fun = this; } // 这个打印很重要, // 看明白了这里, // 也就明白了this改变的缘由了 // context: { sname: '陆游', age: 85, fun: [Function: applyFun] } // 这不就是在一个对象里定义属性吗 // 一个属性是值 // 一个属性是函数 // 在同一对象中, // 当函数调用时回去找自己身上有没有这个属性, // 没有就往上一级找 // 上一级就是对象里的属性值啦 // 然后不就达到改变this只想的目的了吗 console.log('context:', context); // 如果args不是数组, // 并且也不等与 undefined if (!Array.isArray(args) && args != undefined) { throw new TypeError(args + ' is not a array'); } // 如果存在参数, // 传递参数, // 并调用函数 // 否则直接调用函数 if (args != undefined) { context.fun(args); } else { context.fun([]); } // 将属性删除 delete context.fun; // 返回调用后的结果 return context; };3.2、被调用的函数
function applyFun(args) { let conResult = `${args[0]} ${this.sname},${args[1]} ${this.age} ${args[2]}。`; console.log(conResult); // my name is 陆游,享年85岁。 return { sname: this.sname, age: this.age }; };3.3、被指向的对象
let applyData = { sname: "陆游", age: 85, };3.4、函数调用
let applyResult = applyFun.myapply(applyData, ['my name is', '享年', '岁']); console.log(applyResult); // {sname: "陆游", age: 85}