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

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

问题描述

我对正确使用 apply 或 call 方法感到困惑.我知道 apply 将数组传递给函数,而 call 将字符串传递给函数.例如下面的代码,这个"到底与代码有什么关系?如果它与此代码无关,那么任何人都可以举个例子,说明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.

请参阅:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply

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

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