绑定,应用和调用方法之间的区别? [英] Difference between bind, apply and call method?

查看:82
本文介绍了绑定,应用和调用方法之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在stackoverflow和web中搜索,无法获得正确的结果或解释这三种方法之间的区别。

I was searching in stackoverflow and the web, could not get proper results or explanation siting difference between these three methods.

据我所知,他们都在不同的上下文中执行相同的函数/方法。

As far as i understand, they all do the same executing the function/method in different context.

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

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

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

This is my normal function of the google object. Now when i make use of call and bind method here, here is the output.

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

我仍然没有看到这样做的目的,我可以继续打电话给 google.makeBeer三次使用不同的参数。

I still don't see a purpose of doing this, i can go-ahead and call the google.makeBeer three times with different arguments.

任何人都可以通过此更多地启发我。

Can anyone enlighten me more over this.

推荐答案

apply call 是同样的事情,除了一个接受以参数形式传递给数组形式的函数的参数。

apply and call are the same thing except one accepts the arguments to be passed to the function in array form the other in parameter form.

bind 调用或<相同code> apply 取决于您使用的框架,但不会立即调用该函数,而是返回一个新函数,其参数绑定到 this 当从新范围或上下文调用该函数时,仍将保留您绑定的任何内容。绑定还允许您防止构造函数被 apply 调用黑客攻击,因为它始终使用绑定的参数,无论有人发送什么来尝试通过调用来覆盖 c $ c>或申请

bind does the same thing as call or apply depending on the framework you are using but doesn't call the function right away instead it returns a new function with your parameters bound to this and when the function is called from a new scope or context, this will still remain whatever you bound to it. Binding also allows you to prevent your constructors from being "hacked" by apply or call since it will always use the binded parameters for this no matter what someone sends to attempt to override this via call or apply.

以下是一个例子:

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

这篇关于绑定,应用和调用方法之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆