Js中call/apply/bind方法函数的原生实现

更新日期: 2019-07-05阅读: 1.6k标签: this

call/apply/bind方法简介

在JavaScript中,函数中this的指向往往在调用时才可确定,而JavaScript提供了call/apply/bind方法让我们得以显示绑定函数的this指向。它们的第一个参数是一个对象,它们会把这个对象绑定到调用他们的函数内的this。因为你可以直接指定 this 的绑定对象,因此我们称之为显式绑定。

//用例
var a = { q: 1 };
var b = { q: 2 };
var c = { q: 3 };
function cs(s) {
    console.log(this.q)
}
cs.bind(a)();//1
cs.call(b);//2
cs.apply(c);//3


tips

var s = new fn.myBind({ a: 2333 })();//报错!!,运算优先级:属性访问>带参new>函数调用>无参new
var s = new (fn.myBind({ a: 2333 }))();//正确姿势


自定义Call方法实现

参数从arguments[1]开始,func.myCall(obj:Object[,agr1:any[,agr2:any[...]]])

if (!Function.prototype.myCall) {
    Function.prototype.myCall = function (targetThis) {
        //targetThis默认为windows(严格模式不允许)
        targetThis = targetThis || window;
        //利用对象调用指定this
        targetThis.fn = this;
        //收集参数
        var agrs = [];
        //因为arguments[0]===targetThis,故从下标1开始
        for (var ge = 1, len = arguments.length; ge < len; ge++) {
            agrs.push('arguments[' + ge + ']');
        }
        //利用eval展开参数 并执行函数
        var result = eval('targetThis.fn(' + agrs + ')');
        //删除附加对象的属性以消除副作用
        delete targetThis.fn;
        //返回结果
        return result;
    }
}


自定义apply方法实现

参数放在数组里func.call(obj:Object[,agr:Array])

if (!Function.prototype.myApply) {
    Function.prototype.myApply = function (targetThis, arrAgrs) {
        //targetThis默认为windows(严格模式不允许)
        targetThis = targetThis || window;
        //利用对象调用指定this
        targetThis.fn = this;
        var agrs = [];
        //收集参数数组
        for (var ge = 0, len = arrAgrs.length; ge < len; ge++) {
            agrs.push('arrAgrs[' + ge + ']');
        }
        //利用eval展开参数 并执行函数
        var result = eval(' targetThis.fn(' + agrs + ')');
        //删除附加对象的属性以消除副作用
        delete targetThis.fn;
        //返回结果
        return result;
    }
}


自定义bind方法实现

参数从arguments[1]开始,func.myCall(obj:Object[,agr1:any[,agr2:any[...]]])

//考虑参数合并以及new优先级和原型继承
if (!Function.prototype.myBind) {
    Function.prototype.myBind = function (targetThis) {
        //若非函数对象来调用本方法,报异常
        if (typeof this !== "function") {
            throw new TypeError(
                "Function.prototype.bind error"
            );
        }
        //收集参数
        var bindArgs = Array.prototype.slice.call(arguments, 1),
            originFunction = this,//保存原始this(原始函数)
            fnProto = function () { },//利用空函数间接链接prototype以应对new时的原型继承
            fnBounding = function () {
                //考核new操作this绑定优先
                return originFunction.apply(
                    (
                        this instanceof fnProto ? this : targetThis
                    ),
                    bindArgs.concat(
                        Array.prototype.slice.call(arguments)
                    )
                )
            };
        fnProto.prototype = this.prototype;//链接原型
        //new一个fnProto以实现简洁继承原型,防止对fnBounding.prototype的操作污染originFunction原型prototype
        fnBounding.prototype = new fnProto();
        return fnBounding;
    };
}


软绑定

bind之后可以再bind或call/apply

if (!Function.prototype.softBind) {
    Function.prototype.softBind = function (obj) {
        var fn = this;
        // 捕获所有 curried 参数
        var curried = [].slice.call(arguments, 1);
        var bound = function () {
            return fn.apply(
                (!this || this === (window || global)) ?
                    obj : this,
                curried.concat.apply(curried, arguments)
            );
        };
        bound.prototype = Object.create(fn.prototype);//链接原型
        return bound;
    };
}

链接: https://www.fly63.com/article/detial/4532

解读Javascript中的this机制,别再为了 this 发愁了

JavaScript中有很多令人困惑的地方,或者叫做机制。但是,就是这些东西让JavaScript显得那么美好而与众不同。比方说函数也是对象、闭包、原型链继承等等,而这其中就包括颇让人费解的this机制。

js中this的详细解释,JavaScript中this绑定规则【你不知道的JavaScript】

this的绑定过程之前的调用栈 和 调用位置,this绑定规则:1、默认模式,2、隐式绑定,3、显式绑定,4、new绑定

JavaScript中this的运行机制及爬坑指南

在 JavaScript 中,this 这个特殊的变量是相对比较复杂的,因为 this 不仅仅用在面向对象环境中,在其他任何地方也是可用的。 本篇博文中会解释 this 是如何工作的以及使用中可能导致问题的地方,最后奉上最佳实践。

JS中this的指向问题(全)

this关键字在js中的指向问题不管是工作还是面试中都会经常遇到,所以在此对它进行一下总结:全局作用域中、闭包中指window、函数调用模式:谁调用就指谁、构造函数中,this指实例对象、apply/call改变this的指向、bind改变this指向等

彻底淘汰并消除JavaScript中的this

如果这很难明白,为什么我们不停止使用它呢?认真的思考一下?如果你读过 将90%的垃圾扔进垃圾桶后,我如何重新发现对JavaScript的爱, 当我说扔掉它时,你不会感到惊讶,this被丢弃了

JavaScript this常见指向问题

this的用法:直接在函数中使用 谁调用这个函数this就指向谁 ,对象中使用, 一般情况下指向该对象 ,在构造函数中使用

JavaScript函数中this的四种绑定策略

this的四种绑定策略:默认绑定、隐式绑定、显示绑定、new绑定。首先要明确的是一般情况下,this不是函数被定义时绑定,而是函数被调用时被绑定 ,那么函数中的this有四种绑定方式:

改变this的指向

this是Javascript语言的一个关键字。它代表函数运行时,自动生成的一个内部对象.this永远指向函数的调用者。随着函数使用场合的不同,this的值会发生变化。但是有一个总的原则,那就是this指的是,调用函数的那个对象。

js手写实现apply,call,bind

apply和call的区别就是传的参数形式不一样。call是一个一个的传,apply可以将参数以数组的形式传进去。而bind是传入第二个和后面的参数,且绑定this,返回一个转化后的函数。

this指向问题的经典场景

以函数形式调用,this指向window;以方法形式调用,this指向调用方法的那个对象;构造函数调用,this指向实例的对象;使用window对象的方法使,指向window;多重场景改变this指向

点击更多...

内容以共享、参考、研究为目的,不存在任何商业目的。其版权属原作者所有,如有侵权或违规,请与小编联系!情况属实本人将予以删除!