使用模拟实现的方式探究call 和 apply 的原理

使用模拟实现的方式探究call 和 apply 的原理

call

作用:

call() 方法就是在使用一个指定 this 值和若干个指定的参数值的前提下调用某个函数或者方法。

var foo = {
    value : 1
}
function bar() {
    console.log(this.value)
}
// 如果不对this进行绑定执行bar() 会返回undefined
bar.call(foo) // 1

也就是说call()改变了 this 的指向到了 foo

下面进行一下模拟实现

试想当调用 call 的时候,也就是类似于

var foo = {
    value: 1,
    bar: function() {
        console.log(this.value)
    }
}
foo.bar() // 1

这样就把 this 指向到了 foo 上,但是这样给 foo 对象加了一个属性,有些瑕疵,不过不要紧,执行完删除这个属性就可以完美实现了。

也就是说步骤可以是这样:

  1. 将函数设为对象的属性
  2. 执行这个函数
  3. 删除这个函数

下面就试着去实现一下:

Function.prototype.call2 = function(context) {
    context.fn = this // this 也就是调用call的函数
    var result = context.fn()
    delete context.fn()
    return result
}

var foo = {
    value: 1
}
function bar() {
    console.log(this.value)
}
bar.call2(foo) // 1

但是这样有一个小缺陷就是call() 不仅能指定this到函数,还能传入给定参数执行函数比如:

var foo = {
    value: 1
}
function bar(name, age) {
    console.log(name)
    console.log(age)
    console.log(this.value)
}
bar.call(foo, 'black', '18')
// black
// 18
// 1

特别要注意的一点是,传入的参数的数量是不确定的,所以我们要使用arguments 对象,取出除去第一个之外的参数,放到一个数组里:

Function.prototype.call2 = function(context) {
    context.fn = this // this 也就是调用call的函数
    var args = [...arguments].slice(1)
    var result = context.fn(...args)
    delete context.fn()
    return result
}

var foo = {
    value: 1
}
function bar(name, age) {
    console.log(name)
    console.log(age)
    console.log(this.value);
}
bar.call2(foo, 'black', '18') // black 18 1

还有一点需要注意的是,如果不传入参数,默认指向为 window,所以最终版代码:

Function.prototype.call2 = function(context) {
    var context = context || window
    context.fn = this // this 也就是调用call的函数
    var args = [...arguments].slice(1)
    var result = context.fn(...args)
    delete context.fn()
    return result
}
var value = 1
function bar() {
    console.log(this.value)
}
bar.call2()

apply

apply的方法和 call 方法的实现类似,只不过是如果有参数,以数组形式进行传递,直接上代码:

Function.prototype.apply2 = function(context) {
    var context = context || window
    context.fn = this // this 也就是调用apply的函数
    var result
    // 判断是否有第二个参数
    if(arguments[1]) {
        result = context.fn(...arguments[1])
    } else {
        result = context.fn()
    }
    delete context.fn()
    return result
}

var foo = {
    value: 1
}
function bar(name, age) {
    console.log(name)
    console.log(age)
    console.log(this.value);
}
bar.apply2(foo, ['black', '18']) // black 18 1
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,026评论 19 139
  • 函数和对象 1、函数 1.1 函数概述 函数对于任何一门语言来说都是核心的概念。通过函数可以封装任意多条语句,而且...
    道无虚阅读 4,665评论 0 5
  • 本文首发我的个人博客:前端小密圈,评论交流送1024邀请码,嘿嘿嘿😄。 来自朋友去某信用卡管家的做的一道面试题,用...
    微醺岁月阅读 3,231评论 4 32
  • 朱大大发来的照片,让我又回想起在北京的日子。人只有不停地去做,不要停下来才能无限接近目标。接下来的两个星期公司强行...
    叶子卷阅读 325评论 0 2
  • 书桌 放满 想给你的 信笺 电台 播放着 那首 你最喜欢 的旋律 想你 若隐若现 的笑脸 恨不能 每天 都能够 看...
    简言笔下阅读 156评论 0 0