优秀的编程知识分享平台

网站首页 > 技术文章 正文

call和apply的实现方式(apply和call的使用场景)

nanyue 2025-07-07 21:51:47 技术文章 2 ℃

call和apply的实现方式


1、函数Function.call()的实现

//第一步简单是实现 call()

var foo ={

value:”1”,

bar:function(){

console.log(this.value)

}

}

foo.bar(); //1

//第二种 复杂的实现

Function.prototype.call2=function(content = window ){

content.fn = this;

let args = [...arguments].slice(1);

let result = content.fn(...args);

delete content.fn;

return result;

}

var foo={

value:1

}

function bar(name, age) {

console.log(name)

console.log(age)

console.log(this.value);

}

bar.call2(foo,’black’,'18’);// black 18 1

2、函数Function.apply()的实现

Function.prototype.aplly2 = function(content = window){

content.fn = this

let result;

// 判断是否有第二个参数

if(arguments[1]) {

result = content.fn(...arguments[1])

} else {

result = content.fn()

}

delete content.fn()

return result

}

var foo={

value:1

}

function bar(name, age) {

console.log(name)

console.log(age)

console.log(this.value)

}

bar.aplly2(foo,['black','18'])// black 18 1

注意:

Call() 和 apply()方法相似,只是传参方式不同,其中call 为字符串 arg1,arg2,…..而apply为数组[arg1,arg2…..]

Tags:

最近发表
标签列表