实现bind兼容的函数,调用结果一直是undefined

/*bind的兼容性实现 /

Function.prototype.bindFun = function(thisObj) {
    // 获取函数本身,调用bind的函数对象
    var _func = this;
    var _params = Array.prototype.slice.call(arguments, 1);
    if (!Function.prototype.bind) {
           alert("不支持bind方法");
            if (typeof this !== "function") {
                throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
            }
           // 获取函数调用者(bind方法的第一个参数)
            var  _this = thisObj;
            // 返回一个函数,外部变量通过持有这个函数引用保存_func,_this,_params这三个闭包变量,并随时执行函数以调用下面语句。
            return function(){
                var _localParams = Array.prototype.slice.call(arguments);
                _params = _params.concat(_localParams);
                _func.apply(_this, _params); // 实现函数调用

            };

    }
    else {
        alert("支持bind方法");
        console.log(_func);
        return _func.bind(thisObj,_params);

    }

};

function move(x, y) {
    this.x += x;
    this.y += y;
}
var point = {x:1, y:2};
var pointmove = move.bindFun(point, 2, 2);
console.log(pointmove()); // undefined 这个结果怎么不是{x:3,y:3}
阅读 3.6k
3 个回答

首先你的move函数没写返回值。
然后这一步:_func.bind(thisObj,_params)
相当于move.bind({x:1, y:2},[2,2])
bind里传递参数是要分开传的和apply不一样。[2,2]作为了movex参数被传了进去。所以就算写了返回值,得到的也不是你要的结果。

move没有return。默认return的是undefined

给你个改版的

Function.prototype.bindFun = function(thisObj) {
    // 获取函数本身,调用bind的函数对象
    var _func = this;
    var _params = Array.prototype.slice.call(arguments, 1);
    if (!Function.prototype.bind) {
           alert("不支持bind方法");
            if (typeof this !== "function") {
                throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
            }
           // 获取函数调用者(bind方法的第一个参数)
            var  _this = thisObj;
            // 返回一个函数,外部变量通过持有这个函数引用保存_func,_this,_params这三个闭包变量,并随时执行函数以调用下面语句。
            return function(){
                var _localParams = Array.prototype.slice.call(arguments);
                _params = _params.concat(_localParams);
                _func.apply(_this, _params); // 实现函数调用

            };

    }
    else {
        console.log(_func);
        return _func.bind(thisObj);

    }

};

function move(x, y) {
  this.x += x;
  this.y += y;

  return this
}
var point = {x:1, y:2};
var pointmove = move.bindFun(point);
console.log(pointmove(2, 2));
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题