Skip to content Skip to sidebar Skip to footer

Apply/call Method In Javascript: What Is The First Arguments "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 belo

Solution 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.

functionfoo(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.barconsole.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

Solution 2:

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

functiontest() {
    alert(this.a);
}

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

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

}());

Solution 3:

The first argument will be the this in your function.

ie:

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

Post a Comment for "Apply/call Method In Javascript: What Is The First Arguments "this"?"