js/javascript : apply,call,bind三者的使用与区别

参考:

apply,call,bind三者的使用与区别

每个函数都包含两个非继承而来的方法:call()apply()
在JavaScript中,call和apply作用是一样的,都是为了改变某个函数运行时的上下文(context)而存在的,换句话说,就是为了改变函数体内部this的指向

一、方法介绍:


interface NewableFunction extends Function {
    /**
     * 以指定对象作为 this 值,以指定[数组]的元素作为参数调用函数。
     * @param thisArg 用作 this 对象的对象。
     * @param args 要传递给函数的参数值[数组]。
     */
    apply<T>(this: new () => T, thisArg: T): void;
    apply<T, A extends any[]>(this: new (...args: A) => T, thisArg: T, args: A): void;

    /**
     * 使用指定的对象作为 this 值和指定的其余参数作为参数调用函数。
     * @param thisArg 用作 this 对象的对象。
     * @param args 要传递给函数的参数值。
     */
    call<T, A extends any[]>(this: new (...args: A) => T, thisArg: T, ...args: A): void;

    /**
     * 对于给定的函数,创建一个与原始函数具有相同主体的[绑定函数]。返回的是函数
     * 绑定函数的 this 对象与指定的对象相关联,并具有指定的初始参数。
     * @param thisArg 用作 this 对象的对象。
     * @param args 绑定到函数参数的参数。
     */
    bind<T>(this: T, thisArg: any): T;
}

二、详细介绍

callapplybind都可以改变函数运行时的上下文,也就是函数体内部的this指向
其中call和apply非常相似,他们的区别仅仅体现在参数形式的不同

所以我们先介绍call及apply。

1.call和apply

javascript的函数体内的上下文可以在运行时改变。看下面的代码

function Cat(name){
    this.name = name
    this.sayHi = function(){
       console.log("hi,I am " + this.name) 
    }
}
 
function Mouse(name){
    this.name = name
}
 
var cat = new Cat("Tom")
cat.sayHi()   // hi, I am Tom
var mouse = new Mouse("Jerry")
mouse.sayHI()  // Uncaught TypeError: mouse.sayHI is not a function

上面代码先创建了一个Cat类的实例对象cat并调用了其sayHi方法。在sayHi被调用时,其内部的this指向的是cat实例。

接下来我创建了一个mouse对象,也想调用sayHi方法,
显而易见因为Mouse构造函数的定义中没有sayHi这个方法从而导致报错。

那么有没有简单的方式可以直接调用到Cat类中的sayHi方法呢。
答案是肯定的,那就是借助call和apply实现。

cat.sayHi.call(mouse)  //hi,I am Jerry
cat.sayHi.apply(mouse)  //hi,I am Jerry

可以看到两种方式都可以实现我们想要的效果。其原因是在调用call和apply的时候,
sayHi函数内部的this指向变成了我们传入call和apply方法的第一个参数对象mouse。

上面的调用方式看不出call和apply的具体区别。我们稍微修改一下代码

function Cat(name){
    this.name = name
    this.sayHi = function(age, favor){
       console.log("hi,I am " + this.name + "," + age + " years old,I like " + favor) 
    }
}
 
function Mouse(name){
    this.name = name
}
 
var cat = new Cat("Tom")
cat.sayHi(12, "fish")   // hi,I am Tom,12 years old,I like fish
var mouse = new Mouse("Jerry", 8, "cheese")
//mouse.sayHI(10, "cheese")  // Uncaught TypeError: mouse.sayHI is not a function
 
cat.sayHi.apply(mouse, [10, "cheese"])  // hi,I am Jerry,10 years old,I like cheese
cat.sayHi.call(mouse, 10, "cheese")  // hi,I am Jerry,10 years old,I like cheese

可以看到当给sayHi函数加入了参数之后,调用apply和call 也可以为sayHi传递参数。
两者传递参数的方式是有区别的,这也是call和apply仅有的区别。
apply使用数组传递参数call是按顺序传递参数

使用方式如下:

fn.apply(thisObj, [param1,param2,param3])
fn.call(thisObj, param1, param2, param3)

apply与call在使用方式上的区别还使得apply有些特殊的用法。
比如:如何使用push方法,不用循环完成两个数组的合并。

var arr1 = [ 1, 2, 3 ]
var arr2 = [ 4, 5, 6 ]

Array.prototype.push.apply(arr1, arr2)  // 6 push方法的返回值是合并后数组的长度
console.log(arr1) // [ 1, 2, 3, 4, 5, 6]

因为apply的第二个参数可以直接接受数组,因此在不确定具体有多少参数的时候,推荐使用apply方法。

2.bind

bind方法也可以改变函数运行时的上下文

applycall的区别在于,bind方法的返回值是 已经改变了this指向的函数必须手动调用才会执行这个函数,而applycall立即执行

再次修改上面的代码:

function Cat(name){
    this.name = name
    this.sayHi = function(age, favor){
       console.log("hi,I am " + this.name + "," + age + " years old,I like " + favor) 
    }
}
 
function Mouse(name){
    this.name = name
}
 
var cat = new Cat("Tom")
cat.sayHi(12, "fish")   // hi,I am Tom,12 years old,I like fish
var mouse = new Mouse("Jerry", 8, "cheese")
//mouse.sayHI(10, "cheese")  // Uncaught TypeError: mouse.sayHI is not a function
 
cat.sayHi.apply(mouse, [10, "cheese"])  // hi,I am Jerry,10 years old,I like cheese
cat.sayHi.call(mouse, 10, "cheese")  // hi,I am Jerry,10 years old,I like cheese
cat.sayHi.bind(mouse, 10, "cheese")()  // hi,I am Jerry,10 years old,I like cheese

区别在最后一行 cat.sayHi.bind(mouse, 10, “cheese”)() 。
可以看到与apply和call相比,在bind()方法后还有个(),这正说明了bind方法返回的是一个函数,并不执行,需要手动去调用才会执行。其返回结果与前两者相同。

总结:

  • applycallbind 三者都可以改变函数内部的this指向
  • applycallbind 三者第一个参数都是this要指向的对象,也就是想指定的上下文
  • applycallbind 三者都可以利用后续参数传参
  • 后续参数的传递:apply使用数组传递参数,callbind按顺序传递参数
  • bind 返回this指向已经变化的函数,需要手动调用applycall 则是在指向变化后立即调用;

demo1 :

function add(a, b) {
    return a + b;
}

function sub(a, b) {
    return a - b;
}

console.log(add.call(sub, 2, 1));//3
console.log(add.apply(sub, [2, 1]));//3
console.log(add.bind(sub, 2, 1)());//3

demo2:

function People(name, age) {
    this.name = name;
    this.age = age;
}

function Student1(name, age, grade) {
    People.call(this, name, age);
    this.grade = grade;
}

function Student2(name, age, grade) {
    People.apply(this, [name, age]);
    this.grade = grade;
}

function Student3(name, age, grade) {
    People.bind(this, name, age)();
    this.grade = grade;
}

var student1 = new Student1('小明1', 21, '大一');
console.log(student1.name + "-" + student1.age + "-" + student1.grade);

var student2 = new Student2('小明2', 22, '大二');
console.log(student2.name + "-" + student2.age + "-" + student2.grade);

var student3 = new Student3('小明3', 23, '大三');
console.log(student3.name + "-" + student3.age + "-" + student3.grade);
// 小明1-21-大一
// 小明2-22-大二
// 小明3-23-大三
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值