CNode

bind用法求解,请大家帮帮忙

119098860发布于12 年前最后回复12 年前8 回复9844 浏览0 收藏

最近研究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)

1
19098860#1·12 年前

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

Z
zengwenbing#3·12 年前

个人理解的: 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: => 下片
Z
zengwenbing#4·12 年前

pomelo的没用过,呵呵

X
xujun52011#5·12 年前

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

var fn2 = fn.bind(document);

fn2.call(window);

你可以执行以下...

D
dead-horse#6·12 年前
引用 19098860还有个问题,为什么要bind?直接调用onUserLeave不行么?怎么感觉多此一举

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

session.on('close', function () {
  var args = Array.prototype.slice.call(arguments);
  args.unshift(self.app);
  onUserLeave.apply(null, args);
});
L
liyisheng#7·12 年前

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');

A
alsotang#8·12 年前
引用 19098860还有个问题,为什么要bind?直接调用onUserLeave不行么?怎么感觉多此一举

@dead-horse

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

参与回复
登录后即可参与回复。登录