zoukankan      html  css  js  c++  java
  • 《javascript设计模式与开放实践》学习(二)Function.prototype.bind

    使用Function.prototype.bind来包装func函数

    1、简化版的bind

    Function.prototype.bind=function (context) {
            var self=this; //保存原函数
            return function () {
                return self.apply(context,arguments);
            }
        };
        var obj={name:'seven'};
        var func=function(){
            alert(this.name);
        }.bind(obj);
    
        func();

    2、含参数的bind

    Function.prototype.bind=function()  {
            var self=this;
            context=[].shift.call(arguments);//需要绑定的this上下文
            args=[].slice.call(arguments);//剩余的参数
            return function () {
                return self.apply(context,[].concat.call(args,[].slice.call(arguments)));
           //等同于
    return self.apply(context,args.concat(arguments));此arguments后传入的参数
    }; } var obj={name:'seven'}; var func=function(a,b,c,d){ alert(this.name);//输出seven alert([a,b,c,d]);//输出[1,2,3,4] }.bind(obj,1,2) func(3,4);

    注:

    1)arguments对象: arguments 对象并不是一个数组,访问单个参数的方式与访问数组元素的方式相同。

    2)shift用法:用于把数组的第一个元素从其中删除,并返回第一个元素的值。

    2)slice用法:slice() 方法可从已有的数组中返回选定的元素。

    3)concat用法:concat() 方法用于连接两个或多个数组。

  • 相关阅读:
    halcon7月license
    软设考试成绩查询结果
    Halcon自学笔记
    Window_Store
    Windows_Store之2048
    基于C#开发的2048
    MVC+EF+EasyUI实现CRUD
    ASP.NET MVC Model验证总结
    浙江省三级数据库考试
    基于C#的短信发送
  • 原文地址:https://www.cnblogs.com/GallopingSnail/p/5869918.html
Copyright © 2011-2022 走看看