Apply/Call method in Javascript: What is the first arguments “this”?

寵の児 提交于 2019-12-02 10:05:03

问题


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

回答1:


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.

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




回答2:


this is the scope of the Apply/Call function. An example is:

function test() {
    alert(this.a);
}

(function () {
    this.a = "test";
    test();//test

    var self = this;

    (function () {
        this.a = "Foo";
        test();//Foo
        test.apply(self, []);//test
    }());

}());



回答3:


The first argument will be the this in your function.

ie:

var p = {"name":"someone"};
function myFunction(a, b) {
     console.log(this);
     return a*b;
}
var myArray = [10,2];
myFunction.apply(p, myArray); //log output shows {"name":"someone"}


来源:https://stackoverflow.com/questions/29483297/apply-call-method-in-javascript-what-is-the-first-arguments-this

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!