重写Function.prototype.bind

简介: 重写Function.prototype.bind

正文


bind 方法创建一个新的函数,在 bind() 被调用时,这个新函数的 this 被指定为 bind() 的第一个参数,而其余参数将作为新函数的参数,供调用时使用。


Usage: function.bind(thisArg [, arg1 [, arg2 [, ...]]])


参数 thisArg


  • 如果使用 new 运算符构造绑定函数,则忽略该值。
  • 当使用 bind 在 setTimeout 中创建一个函数(作为回调提供)时,作为 thisArg 传递的任何原始值都将转换为 object。
  • 如果 bind 函数的参数列表为空,执行作用域的 this 将被视为新函数的 thisArg。


参数 arg1、arg2...


当目标函数被调用时,被预置入绑定函数的参数列表中的参数。


返回值


返回一个原函数的拷贝,并拥有指定的 this 值和初始参数。


重写 bind 方法


var point = {
    x: 0,
    y: 0,
    z: 0
}
// 构造函数
function Point(x, y, z) {
    console.log(this.x, x, y, z)
    console.log('')
}
// 函数名写成 bindy,是为了方便与原生 bind 方法对比
Function.prototype.bindy = function(context) {
    var _this = this;
    var args = Array.prototype.slice.call(arguments, 1);
    var tempFn = function() {};
    var fn = function() {
        var thatArgs = Array.prototype.slice.call(arguments)
        _this.apply(this instanceof _this ? this : context, args.concat(thatArgs))
    }
    // 圣杯模式
    tempFn.prototype = this.prototype;
    fn.prototype = new tempFn();
    return fn;   
}
// bind 可以在调用的时候传入参数
Point.bind(point, 1, 2)(3);     // output: 0 1 2 3
Point.bindy(point, 4, 5)(6);    // output: 0 4 5 6
// 使用 new 去构造时,bind 绑定的 this 最终会执行构造函数
let p = Point.bind(point);
let p2 = Point.bindy(point);
new p(3, 3, 3);                 // output: undefined 3 3 3
new p2(4, 4, 4);                // output: undefined 4 4 4


目录
相关文章
|
23天前
|
JavaScript 前端开发
JavaScript中Object.prototype.toString.call()、instanceOf和Array.isArray()的区别
JavaScript中Object.prototype.toString.call()、instanceOf和Array.isArray()的区别
23 1
|
3月前
|
C++
C++11 function、bind、可变参数模板
C++11 function、bind、可变参数模板
27 0
|
7月前
|
JavaScript 前端开发
原型链中:为什么Function.proto==Function.prototype?
原型链中:为什么Function.proto==Function.prototype?
|
12月前
|
JavaScript 前端开发
Function() 构造函数
Function() 构造函数
46 0
|
JavaScript
JS:Function对象call、apply、bind改变this指向
JS:Function对象call、apply、bind改变this指向
|
Web App开发 JavaScript 前端开发
三千文字,也没写好 Function.prototype.call
Function.prototype.call,手写系列,万文面试系列,必会系列必包含的内容,足见其在前端的分量。 本文基于MDN 和 ECMA 标准,和大家一起从新认识call。
132 0
三千文字,也没写好 Function.prototype.call
Element.prototype.addDependent will call addAggregation
Element.prototype.addDependent will call addAggregation
104 0
Element.prototype.addDependent will call addAggregation
一段代码看懂原型对象中的callback
一段代码看懂原型对象中的callback
109 0
一段代码看懂原型对象中的callback
|
算法 JavaScript
第197天:js---caller、callee、constructor和prototype用法
一、caller---返回函数调用者 1 //返回函数调用者 2 //caller的应用场景 主要用于察看函数本身被哪个函数调用 3 function fn() { 4 //判断某函数是否被调用 5 if (fn.
1307 0