在Javascript中应用/调用方法:第一个参数是什么?“这个”? [英] Apply/Call method in Javascript: What is the first arguments "this"?

查看:107
本文介绍了在Javascript中应用/调用方法:第一个参数是什么?“这个”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对正确使用apply或call方法感到困惑。
我知道apply是将数组传递给函数,并且调用是将字符串传递给函数。
例如下面的代码,this与代码有什么关系?如果它与此代码无关,那么当this正在适当实现时,任何人都可以给我一个例子吗?

I am confused about using apply or call method correctly. I know that apply is passing an array to the function and call is passing strings to a function. For example the code below, what does "this"really have to do with the code? if it has nothing to do with this code, then can anyone give me an example when "this" is implementing appropriately?

function myFunction(a, b) {
    return a * b;
}
myArray = [10,2];
myFunction.apply(this, myArray);




推荐答案

这是上下文为功能。如果你在函数中有this.something,它将从该上下文对象访问该特定属性。

It's the context for the function. If you have this.something inside the function, it will access that particular property from that context object.

    

    function foo(bar) {
        this.bar = bar;
    }
    
    foo.apply(this, ['Hello']);    //calling foo using window as context (this = window in global context in browser)
    console.log(this.bar);         //as you can see window.bar is the same as this.bar
    console.log(window.bar);
    
    var ctx = {};    //create a new context
    
    foo.apply(ctx, ['Good night']);
    console.log(ctx.bar);        //ctx now has bar property that is injected from foo function

Open up your dev console to see result.

请参阅:< a href =https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply =nofollow> https://developer.mozilla.org/en- US / docs / Web / JavaScript / Reference / Global_Objects / Function / apply

这篇关于在Javascript中应用/调用方法:第一个参数是什么?“这个”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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