• 手写源码 -- bind,call,aplly


    bind

    • bind用法fn.bind(thisobj,参数1,参数2,。。。)
                this.a = 1;
                var mode = {
                    a: 10,
                    getA: function (...rest) {
                        return rest.reduce((pre, value) => {
                            console.log(pre);
                            return (pre += value);
                        }, this.a);
                    }
                };
                console.warn(mode.getA(1, 2, 3)); //16
    
                var mode2 = mode.getA; //其中的this指向指向window
                console.error(mode2(1, 2, 3)); //7
    
                var mode2 = mode.getA.bind(mode);//其中this指向mode
                console.error(mode2(1, 2, 3)); //16
    

    js写bind函数

                Function.prototype.bindFn = function () {
                    var _this = this;  //保存原函数
                    var context = [].shift.call(arguments);  //保存第一个参数为上下文的this
                    var args = [].slice.call(arguments);  //将剩余的参数整合成数组
                    return function () {
                        return _this.apply(context, [].concat.call(args, [].slice.call(arguments)));
                    };
                };
    

    call和apply是改变this指向,只是参数不一样,call是可以传多个参数,apply是第二个参数是数组

    call

                Function.prototype.callFn = function (content) {
                    content = content || window;
                    content.fn = this;
                    var args = [...arguments].slice(1);
                    var result = content.fn(...args);
                    delete content.fn;
                    return result;
                };
    

    apply

                Function.prototype.applyFn = function (content, args) {
                    if (!(args instanceof Array)) throw new Error('传入需要的是数组');
                    content = content || window;
                    content.fn = this;
                    var result = content.fn(...arguments);
                    delete content.fn;
                    return result;
                };
    
  • 相关阅读:
    C# String.Format格式说明
    jQuery.json.js
    禁止别人使用"另存为"保存你的网页
    组合问题的递归算法
    jQuery,contents()
    C#string,StringBuilder和Regex类的讲解
    jQuery性能优化指南
    加密算法的C#实现
    m,n组合算法
    jQuery插件—获取URL参数
  • 原文地址:https://www.cnblogs.com/douge/p/14557449.html
Copyright © 2020-2023  润新知