1

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);
Someone
  • 147
  • 2
  • 2
  • 9
  • 2
    It is what `this` will refer at *inside* the function. – zerkms Apr 07 '15 at 03:38
  • You might want to refer this : http://stackoverflow.com/questions/1986896/what-is-the-difference-between-call-and-apply – Saagar Elias Jacky Apr 07 '15 at 03:48
  • `call` does not "pass strings to a function", it passes individual arguments or whatever type. Anyway, the `this` argument does what the documentation says it does. Read it. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply. If the function you are calling does not use `this`, then you can pass 0, or null, or undefined, or "123", or anything else you want. –  Apr 07 '15 at 04:27

3 Answers3

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

Jimmy Chandra
  • 6,333
  • 4
  • 24
  • 37
0

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

}());
Downgoat
  • 11,422
  • 5
  • 37
  • 64
0

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"}
slebetman
  • 93,070
  • 18
  • 116
  • 145
Zaid Daghestani
  • 8,285
  • 3
  • 30
  • 43