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

applycall 作用相同,区别在于: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

calleearguments.callee 的一个属性,返回当前正在执行的函数体源代码。

function B() {
    this.print = function () {
        console.log(arguments.callee  + " .......");
    };
    this.print();
}
b = new B();