绑定,应用和调用方法之间的区别?

Kev*_*vin 12 javascript

我在stackoverflow和网络上搜索,无法获得正确的结果或解释这三种方法之间的区别.

据我所知,他们都在执行相同的操作 function/method in different context.

var google = {  
    makeBeer : function(arg1,arg2){     
         alert([arg1, arg2]);        
    }    
}

google.makeBeer('water','soda');
Run Code Online (Sandbox Code Playgroud)

这是我对谷歌对象的正常功能.现在,当我在这里使用call和bind方法时,这里是输出.

var google = {
    makeBeer: function (arg1, arg2) {
        alert([arg1, arg2]);
    }
}

google.makeBeer('water', 'soda');

function yahoo() {}

var yah = new yahoo();
google.makeBeer.call(yah, 'pepsi', 'coke');

function msn() {

}

var msn = new msn();
google.makeBeer.call(msn, 'sprite', 'limca');
Run Code Online (Sandbox Code Playgroud)

我仍然没有看到这样做的目的,我可以反过来打电话给 google.makeBeer three times with different arguments.

任何人都可以在此更多地启发我.

Tha*_*var 13

apply并且call是相同的东西,除了一个接受以参数形式传递给数组形式的函数的参数.

bind做同样的事情callapply取决于您正在使用的框架,但不立即调用该函数而是返回一个新函数,您的参数绑定到this,当从新的作用域或上下文调用该函数时,this仍然会保持不变你受到了约束.绑定还允许您防止构造函数被"黑客攻击" applycall因为它总是使用绑定参数,this无论有人发送什么来尝试覆盖或this通过.callapply

这是一个例子:

function Profile(u) {
    this.user = u;
    this.getUser = function () {
        return this.user;
    };
}

function Profile2(u) {
    this.user = u;
    this.getUser = (function () {
        return this.user;
    });
}

function Profile3(u) {
    this.user = u;
    this.getUser = (function () {
        return this.user;
    });
}

var x = new Profile('guest');
var x2 = new Profile2('guest');
var x3 = new Profile3('guest');

alert(x.getUser.apply({
    user: 'Vinoth'
})); // Vinoth
alert(x2.getUser.call({
    user: 'Babu'
})); // babu
alert(x3.getUser.bind(x3).call({
    user: 'Nandan'
})); // Guest
Run Code Online (Sandbox Code Playgroud)