title: call,apply,bind用法
date: 2018-05-28 23:00:00
tags: call apply bind
categories: 前端
call
var obj = {
name: 'hht',
age : 1
}
function f(name,age){
this.name = name;
this.age = age;
console.log(this.name);
console.log(this.age);
}
f.call(obj,'mmd',18);

image
- call()方法調(diào)用一個函數(shù), 其具有一個指定的this值和分別地提供的參數(shù)(參數(shù)的列表).
- call 的第一個參數(shù)是指定調(diào)用的這個函數(shù)的this ,非嚴格模式下this的值如果是null或者undefine ,那么這個this指向window
- call 第二個以及之后的參數(shù)就是我們的arguments的值
apply
var obj = {
name: 'hht',
age : 1
}
function f(name,age){
this.name = name;
this.age = age;
console.log(this.name);
console.log(this.age);
}
f.apply(obj,['mmd',18]);
f.apply(obj,{0: 'mmd', 1: 18, length: 2});

image
- call()方法的作用和 apply() 方法類似,只有一個區(qū)別,就是 call()方法接受的是若干個參數(shù)的列表,而apply()方法接受的是一個包含多個參數(shù)的數(shù)組, 或偽數(shù)組。
bind
var obj = {
name: 'hht',
age : 1
}
function f(){
for(let i = 0; i < 4; i++)
{
console.log(arguments[i]);
}
console.log(this);
}
var f1Bind = f.bind(obj,'hht',18);
f1Bind();
f1Bind(1,2);

image
- bind 綁定時接受的參數(shù)跟 call 一致.
- bind 不會立即調(diào)用,它會生成一個新的函數(shù),你想什么時候調(diào)就什么時候調(diào)。
- bind 綁定好的this不會改變
- bind 綁定時的給的參數(shù)會成為這個綁定函數(shù)的固定參數(shù),調(diào)用這個函數(shù)時這幾個參數(shù)一定會在