bind用法求解,请大家帮帮忙
发布于 10 年前 作者 19098860 8905 次浏览 最后一次编辑是 8 年前

最近研究pomelo,之前没接触过js,遇到bind这样的用法,完全不知所云。求解。

var onUserLeave = function(app, session) { if(!session || !session.uid) { return; } app.rpc.chat.chatRemote.kick(session, session.uid, app.get(‘serverId’), session.get(‘rid’), null); };

session.on(‘closed’, onUserLeave.bind(null, self.app));

session是怎么传到onUserLeave里面去的呢?另外onUserLeave.bind的第一个参数为什么是null?

8 回复

还有个问题,为什么要bind?直接调用onUserLeave不行么?怎么感觉多此一举

依我愚见,此处的 bind 多此一举。

个人理解的: bind同样是对象冒充,只不过bind只不同于call和apply的是,bind返回的先是类似1个继承了Function.prototype的子类(函数) 内部的实现才是真正的类似Function.prototype.call的。自己封装加了注释

if ( !(Function.prototype.bind ) ) {
  Function.prototype.bind = function ( that ) {
  var args = Array.prototype.slice.call( arguments, 1 ); //获取调用bind方法的参数数组
  var _self = this; // 代表当前Function.prototype
  var funCaller = function () {
   return _self.call( that, args.concat( Array.prototype.slice( arguments ) ) ); //即使当前Function.prototype call调用
  }
  funCaller.prototype = _self.prototype; //bind调用后创建的函数继承与当前Function.prototype
  return funCaller; 
 }	
 
}
function g () {
 console.log( this.name ); 
}
g.prototype = {
 name: '看片'
}
g.bind( { name: '下片' } )();

ps: => 下片

pomelo的没用过,呵呵

function fn(){ console.log(this); }

var fn2 = fn.bind(document);

fn2.call(window);

你可以执行以下…

@alsotang 这个 bind 还是有作用的,等价于

session.on('close', function () {
  var args = Array.prototype.slice.call(arguments);
  args.unshift(self.app);
  onUserLeave.apply(null, args);
});

session.on(‘closed’, onUserLeave.bind(null, self.app));

其中 null 是 当该方法执行时的this 指针 ,self.app 是 该方法调用时默认传入的 第一个参数。

如下所示 : var person = { id: ‘001’, outPut :function(name,job) { console.log( “id :” + this.id + “name :” + name + " job" + job ); } } ;

person.outPut(‘li’,‘nodeJs developer’);

person.id = ‘002’; person.outPut.bind(person,‘liz’);

person.outPut(‘android developer’);

@dead-horse

对的对的。。这个 bind 在这里绑定了一个参数还是有用的。

回到顶部