1、apply()用法
改变this指向
fun.apply(obj) 把fun函数中的this指向了obj。obj为空或undefind就是window
var obj = {
a: 1
}
function fun () {
console.log(this.a)
}
fun() //undefined
fun.apply(obj) //1
var w = 'w'
function fun () {
console.log(this.w)
}
fun() //w
fun.apply() //w
一般入参
var obj = {
a: 1
}
function fun (b, c) {
console.log(this.a)
console.log(b)
console.log(c)
}
fun() //undefined
fun.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 || window
obj.fun = fun
let result
if (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, arr) {
obj = obj || window;
let fn;
obj[fn] = this;
let result;
result = obj[fn](...arr);
delete obj[fn];
return result
}
fun.apply(obj, [2, 3]) //1 2 3