目录
一、call()方法
call() 方法的第一个参数必须是指定的对象,然后方法的原参数,挨个放在后面。
(1)第一个参数:传入该函数this执行的对象,传入什么强制指向什么;
(2)第二个参数开始:将原函数的参数往后顺延一位
var Person = {
name:"lixue",
age:21
}
function fn(x,y){
console.log(x+","+y);
console.log(this);
console.log(this.name);
console.log(this.age);
}
fn.call(Person, "hh", 20);
结果:
二、apply() 方法
apply() 方法的第一个参数是指定的对象,方法的原参数,统一放在第二个数组参数中。
(1)第一个参数:传入该函数this执行的对象,传入什么强制指向什么;
(2)第二个参数开始:将原函数的参数放在一个数组中
var Person = {
name:"lixue",
age:21
}
function fn(x,y){
console.log(x+","+y);
console.log(this);
console.log(this.name);
console.log(this.age);
}
fn.apply(Person, ["hh", 20]);
结果:
三、bind() 方法
bind() 方法的用法和call()一样,直接运行方法,需要注意的是:bind返回新的方法,需要重新
调用
是需要自己手动调用的
var Person = {
name:"lixue",
age:21
}
function fn(x,y){
console.log(x+","+y);
console.log(this);
console.log(this.name);
console.log(this.age);
}
// 方式一
fn.bind(Person, 'hh', 20)()
// 方式二
fn.bind(Person)('hh', 20)
结果: