1. 程式人生 > >js實現bind方法

js實現bind方法

ply obj bing span apply code var creat reat

//目標函數
function fun(...args) {
     console.log(this);
     console.log(args);
}
//目標函數原型對象上的一個方法cher
func.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,3 console.log(newFn2);   //newBind{} console.log(newFn2.cher());   //1

js實現bind方法