//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