JS Function: apply vs call vs bind

智码拓荒者
• 阅读 1692

Function 构造函数中有三个方法可以改变函数实例中的this,今天面试的时候被问到了,懵逼了!今天专门研究了下,发现了一篇不错的文章,半翻译,半理解写在这里。

原文

https://medium.com/@leonardob...

Function.prototype.call()

call允许你调用一个函数,并且在首个参数传入this。然后函数的参数一个一个以逗号分隔,依次传入。
例子:

function greeting(text1, text2) {
  console.log(`${text1} ${this.name}, ${text2}`);
}

let customer1 = { name: 'Leo', email: 'leo@gmail.com' };
let customer2 = { name: 'Nat', email: 'nat@hotmail.com' };

greeting.call(customer1, 'Hello', 'good morning!'); 
// > Hello Leo, good morning!
greeting.call(customer2, 'Hello', 'good afternoon!'); 
// > Hello Nat, good afternoon!

Function.prototype.apply()

这个方法跟call的功能很类似,但是实现方式不太一样。依然是第一个参数传入this,但是被调用的函数的参数会以数组的形式作为apply方法的第二个参数传入。
例子:

function greeting(text1, text2) {
  console.log(`${text1} ${this.name}, ${text2}`);
}

let customer1 = { name: 'Leo', email: 'leo@gmail.com' };
let customer2 = { name: 'Nat', email: 'nat@hotmail.com' };

greeting.apply(customer1, ['Hello', 'How are you?']); 
// > Hello Leo, How are you?
greeting.apply(customer2, ['Hello', 'How are you?']);
// > Hello Natm How are you?

Function.prototype.bind()

这个方法跟callapply很不一样,它不是去调用一个函数,而是根据已有的函数创造了一个新的函数,这个新的函数的this可以在bind参数传入。也就是说新造函数无论什么时候执行,它的this都是固定的。

函数定义:

Function.prototype.bind = function(context) {
  var fn = this;
  return function() {
    fn.apply(context, arguments);
  };
};

这段代码是bind函数的定义,从var fn = this可以知道,fn指向了调用bind函数的函数对象。然后在bind的返回函数fn.apply(context, arguments)可以看出,哪个函数调用了bind,那么bind就把这个函数的this改变为context

例子:

function greeting(text) {
  console.log(`${text} ${this.name}`);
}

let customer1 = { name: 'Leo', email: 'leo@gmail.com' };
let customer2 = { name: 'Nat', email: 'nat@hotmail.com' };

let helloLeo = greeting.bind(customer1);
let helloNat = greeting.bind(customer2);

helloLeo('Hello'); 
// Hello Leo
helloNat('Hello'); 
// Hello Nat

希望能帮助到你!

点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
美凌格栋栋酱 美凌格栋栋酱
6个月前
Oracle 分组与拼接字符串同时使用
SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(
巴拉米 巴拉米
4年前
bind、call、apply 区别?如何实现一个bind?
一、作用call、apply、bind作用是改变函数执行时的上下文,简而言之就是改变函数运行时的this指向那么什么情况下需要改变this的指向呢?下面举个例子var name"lucy";const obj{    name:"martin",    say:function (){        co
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Wesley13 Wesley13
3年前
FLV文件格式
1.        FLV文件对齐方式FLV文件以大端对齐方式存放多字节整型。如存放数字无符号16位的数字300(0x012C),那么在FLV文件中存放的顺序是:|0x01|0x2C|。如果是无符号32位数字300(0x0000012C),那么在FLV文件中的存放顺序是:|0x00|0x00|0x00|0x01|0x2C。2.  
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Stella981 Stella981
3年前
JS 对象数组Array 根据对象object key的值排序sort,很风骚哦
有个js对象数组varary\{id:1,name:"b"},{id:2,name:"b"}\需求是根据name或者id的值来排序,这里有个风骚的函数函数定义:function keysrt(key,desc) {  return function(a,b){    return desc ? ~~(ak
Wesley13 Wesley13
3年前
PHP创建多级树型结构
<!lang:php<?php$areaarray(array('id'1,'pid'0,'name''中国'),array('id'5,'pid'0,'name''美国'),array('id'2,'pid'1,'name''吉林'),array('id'4,'pid'2,'n
Stella981 Stella981
3年前
JavaScript中call()与apply()有什么区别?
今天读《JavaScript权威指南》时发现其中有段代码用到了apply方法用于递归实现数组的展开。可是我不懂这个函数的用法,因此查了一下,将资料整理如下。Javascript的每个Function对象中有一个apply方法:function.apply(thisObj,argArray)还有一个类似功能的call方法:
Python进阶者 Python进阶者
1年前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这