//目标函数function fun(...args) { ????console.log(this); ????console.log(args);}//目标函数原型对象上的一个方法cherfunc.prototype.cher = function () { ???console.log(1);}//bind传入参,一个是要改变this指向的对象,后面的是要传入的实参数值Function.prototype.myBind = function (obj,...args) { ???????var _that = this; ???????//bing会返回一个新的函数 ???????var newBind = function(...list) { ???????????//使用apple方法把this指向改变 ???????????_that.apply(obj,[...list,...args]); ???????} ???????//在用bind改变this指向的时候,返回的函数不会立即执行。如果用返回的函数作为构造函数实例化一个对象的时候,这个对象的原型对象还是目标对象的原型对象,所以要纠正过来 ???????newBind.prototype = Object.create(_that.prototype); ???????newBind.prototype.constructor = _that; ???????//返回这个函数 ???????return newBind;}var fn2 = fun.myBind({a:1},4,3);var newFn2 = new fn2(1,2); ???????????//{a:1} ??1,2,4,3console.log(newFn2); ?????????????? //newBind{}console.log(newFn2.cher()); ??????? //1
js实现bind方法
原文地址:https://www.cnblogs.com/ninefrom/p/9815588.html