//apply用法
function A(alpha,age){
this.name = 'bob';
alert(alpha + arguments[1] + this.name)
}
(function(){
A.apply(this,['a',25])
})()
//call方法
function B(alpha){
this.name = 'alice';
alert(alpha + this.name)
}
(function(){
B.call(this,'b')
})()
//普通函数
function love(alpha){
this.name = 'alice';
alert(alpha + this.name)
}
(function(){
love.call(this,'love')
})()
//async函数
async function create(alpha){
this.name = 'op';
var res = await compute();
alert(alpha + this.name + res)
}
(function(){
create.call(this,'b')
})()
//generator函数
function * gen(num){
console.log(num);
num ++;
yield 'first'
yield 'then'
yield 'final'
return num
}
(function(){
gen.call(this,0)
})()
let it = gen(3);
console.log(it.next()) // {value: "first", done: false}
console.log(it.next()) // {value: "then", done: false}
console.log(it.next()) // {value: "final", done: false}
console.log(it.next()) // {value: "4", done: true}
function compute(){
var num = 0;
for(let i = 0; i < 10 ; i++){//1+2+3+4+5+ ... + 9 =>(1+9)*9/2 = 45
num += i;
}
return num
}
apply和call方法的相同点:
可以使得宿主(当前函数对象)在其自己作用域进行执行,比如在第一个实例中,使用call和apply的第一个参数context(上下文),也可称为this对象,传递给构造函数A,此时this的作用域为当前构造函数A下。
不同点:
传递的参数不同,call第二个参数传递的可以是任何数据类型 函数、数组...,而apply传递的是必须是数组或者类数组。
两个方法该如何选择?
根据你要传入的参数来做选择,不需要传参或者只有1个参数的时候,用call,当要传入多个对象时,用apply
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。