javascript - 实现bind兼容的函数,调用结果一直是undefined
伊谢尔伦
伊谢尔伦 2017-04-11 11:25:49
[JavaScript讨论组]

/*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}
伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

全部回复(3)
巴扎黑

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

黄舟

move没有return。默认return的是undefined

PHP中文网

给你个改版的

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));
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号