zoukankan      html  css  js  c++  java
  • 手写源码 -- 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;
                };
    
  • 相关阅读:
    四则运算实现
    第四周例行报告
    代码规范,结对要求
    第三周例行报告
    第三周作业3功能测试
    第二周例行报告
    第一次作业汇总
    2017/2/24:Maven的pom jar war的区别
    oracle的常用99条语句
    2017/2/21:配置自己的中文乱码拦截器
  • 原文地址:https://www.cnblogs.com/douge/p/14557449.html
Copyright © 2011-2022 走看看