call,bind,apply,caller,callee
a.print() 函数调用等效于 a[“print”]()
1.call
javascript中的call 会更改this(吧调用的对象更改为参数)
function A() {
this.x = 10;
this.print = function () {
console.log(this.x);
};
}
function B() {
this.x = 2;
this.print = function () {
console.log(this.x);
};
}
a = new A();
b = new B();
a.print.call(b); //输出2 ,print内部的this被替换为了b ,所以实际调用的是b的print,等效于b.print()
2.apply
apply 和call作用差不多区别在于call必须把参数列出来,apply是数组,如:
function A() {
this.x = 10;
this.print = function (str ,s2) {
console.log(str + this.x + s2);
};
}
function B() {
this.x = 2;
this.print = function (str,s2) {
console.log(str + this.x + s2);
};
}
a = new A();
b = new B();
a.print.call(b,"... ",0); // print的参数必须给出
a.print.apply(b, ["... ", 0]);// print的参数是数组
3.bind
bind 和其他许多语言的bind都差不多,等效于闭包,提供了一个临时的参数列表。如pomelo中的chat demo
entryHandler.js 中的片段
1.session.on('closed', onUserLeave.bind(null, self.app));
2.session.on('closed', function(){
onUserLeave(self.app,session);
});
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);
};
1和2 是等效的
4.caller
caller属性。返回 调用该函数的函数体(反编译代码)
function B() {
this.x = 2;
var self = this;
this.print = function () {
console.log(self.print.caller + " .......");
};
this.print();//调用者是this ,this指的是function B 所以输出 B的源代码
}
b = new B(); // 输出B的代码
5.callee
callee 是arguments.callee 的一个属性,返回当前正在执行的函数体源代码
function B() {
this.print = function () {
console.log(arguments.callee + " .......");
};
this.print();
}
b = new B();