Function.prototype.call()的使用与实现





Function.prototype

在一个对象的上下文中应用另一个对象的方法;参数能够以数组形式传入。

bind()方法会创建一个新函数,称为绑定函数.当调用这个绑定函数时,绑定函数会以创建它时传入 bind()方法的第一个参数作为 this,传入 bind()方法的第二个以及以后的参数加上绑定函数运行时本身的参数按照顺序作为原函数的参数来调用原函数.

在一个对象的上下文中应用另一个对象的方法;参数能够以列表形式传入。

若函数对象为generator,返回true,反之返回 false

获取函数的实现源码的字符串。 覆盖了 Object.prototype.toSource 方法。

获取函数的实现源码的字符串。覆盖了 Object.prototype.toString 方法。




call()的语法

call与apply 用于显示的设置函数的上下文,两个方法作用一样都是将对象绑定到this,只是在传递参数上有所不同。

  • callapply 都是为了解决改变 this 的指向。作用都是相同的,只是传参的方式不同。

  • call 可以接收一个参数列表

  • apply 只接受一个参数数组。

  • 与 bind 不同 call/apply 会立即执行函数

function show(title) {
    console.log(`${title + this.name}`);
}
let lisi = {
    name: '李四'
};
let wangwu = {
    name: '王五'
};
show.call(lisi, '用户1:');
show.apply(wangwu, ['用户2:']);

// 用户1:李四
// 用户2:王五

一些使用例子

找出数组最大值

let arr = [1, 3, 2, 8];
console.log(Math.max(arr)); //NaN
console.log(Math.max.call(Math, ...arr)); //8
console.log(Math.max.apply(Math, arr)); //8
console.log(Math.max(...arr)); //8

设置函数上下文

<body>
    <button message="这是按钮一">button</button>
    <button message="这是按钮二">button</button>
</body>
<script>
    function show() {
        alert(this.getAttribute('message'));
    }
    let bts = document.getElementsByTagName('button');
    for (let i = 0; i < bts.length; i++) {
        bts[i].addEventListener('click', () => show.call(bts[i]));
    }
</script>

构造属性继承

"use strict";
function Request() {
    this.get = function (params = {}) {
        //组合请求参数
        let option = Object.keys(params)
            .map(i => i + "=" + params[i])
            .join("&");

        return `获取数据 API:${this.url}?${option}`;
    };
}

//文章控制器
function Article() {
    this.url = "article/index";
    Request.apply(this, []);
}



//课程控制器
function Lesson() {
    this.url = "lesson/index";
    Request.call(this);
}



let article = new Article();
console.log(
    article.get({
        row: 10,
        start: 3
    })
);


let lesson = new Lesson();

console.log(
    lesson.get({
        row: 20
    })
);

手动实现一个call()

  • 不传入第一个参数,那么默认为 window
  • 改变 this 指向,让新的对象可以执行该函数
  • 给新的对象添加一个函数func,这个函数的上下文属于传入的this
  • 在执行完以后删除func
Function.prototype.myCall = function(context){
    context = context || window

    // 给context添加一个属性
    // getValue.call(a, 'user1', '24') => a.func = getValue
    context.func = this

    let args = [...arguments].slice(1)

    let result = context.func(...args)
    
    // 删除func
    delete context.func

    return result   
}



let arr = [1, 3, 2, 8];
console.log(Math.max(arr)); //NaN
console.log(Math.max(...arr)); //8
console.log(Math.max.apply(Math, arr)); //8
console.log(Math.max.call(Math, ...arr)); //8
console.log(Math.max.myCall(Math, ...arr)); //8

参考资料

MDN文档

后盾人

前端进阶之道

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值