本文主要是介绍ja apply()用法及手写apply(),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1、apply()用法
改变this指向
fun.apply(obj) 把fun函数中的this指向了obj。obj为空或undefind就是window
var obj = {a: 1}function fun () {console.log(this.a)}fun() //undefinedfun.apply(obj) //1
var w = 'w'function fun () {console.log(this.w)}fun() //wfun.apply() //w
一般入参
var obj = {a: 1}function fun (b, c) {console.log(this.a)console.log(b)console.log(c)}fun() //undefinedfun.apply(obj, [2, 3]) //1 2 3
2、手写apply()
var obj = {a: 1}function fun (b, c) {console.log(this.a)console.log(b, c)}function myApply (fun, obj, arr) {obj = obj || windowobj.fun = funlet resultif (arr) {result= obj.fun(...arr)} else {result= obj.fun()}delete obj.fun //为了避免内存泄漏或者清除不再需要的函数引用return result}myApply(fun, obj, [2, 3])
如果要给函数对象添加新方法如下:
var obj = {a: 1}function fun (b, c) {console.log(this.a)console.log(b, c)}// Function.prototype.myApply = function (obj) {// obj = obj || window;// let fn;// obj[fn] = this;// let result;// result = obj[fn](...arguments[1]);//js把传入到这个函数的全部参数存储在一个叫做arguments的数组里// delete obj[fn];//为了避免内存泄漏或者清除不再需要的函数引用// return result// };//或Function.prototype.myApply = function (obj, arg) {obj = obj || window;let fn;obj[fn] = this;let result;result = obj[fn](...args);delete obj[fn];return result}fun.apply(obj, [2, 3]) //1 2 3
这篇关于ja apply()用法及手写apply()的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!