zoukankan      html  css  js  c++  java
  • JavaScript中bind的模拟实现

    直接上代码了

    Function.prototype.bind2 = function (context) {
        // context 是执行函数时的this指向
        if (typeof this !== "function") {
          throw new Error("only function can use bind");
        }
        var self = this; // 此处的this指向调用bind的函数
        var args = Array.prototype.slice.call(arguments, 1); // 获取除去第一个参数 的参数
    
        var fNOP = function () {};
    
        var fBound = function () {
            var bindArgs = Array.prototype.slice.call(arguments); // bind返回的函数调用时传递的参数
            // 当返回的函数单独调用时,this指向window  this instanceof fNOP为false 
            // 当返回的函数作为构造函数调用时,this指向fBound this instanceof fNOP为true
            return self.apply(this instanceof fNOP ? this : context, args.concat(bindArgs));
        }
    
        fNOP.prototype = this.prototype;
        fBound.prototype = new fNOP();
        return fBound;
    }
    var value = 2;
    var foo = {
        value: 1
    };
    function bar(name, age) {
        this.habit = 'shopping';
        console.log(this.value);
        console.log(name);
        console.log(age);
    }
    
    bar.prototype.friend = 'kevin';
    
  • 相关阅读:
    为何与0xff进行与运算
    智能指针学习笔记
    linux下多线程编程
    redis源码分析之内存布局
    spring
    java
    程序员进修之路
    散列类型(hash)
    字符串类型
    Jmeter使用Websocket插件测试SingalR,外加还有阿里云PTS的Jmeter原生测试爬坑日志。
  • 原文地址:https://www.cnblogs.com/lvzl/p/14778464.html
Copyright © 2011-2022 走看看