theChampion
theChampion

Reputation: 4467

Apply Object In Function

What is the purpose of this.apply(obj); when function is invoked. For example this code.

    Function.prototype.blio = function (a) {
        this.hurka = 'hurka';
        var obj = {};
        this.apply(obj); // what exactly happens here ?
    }

Upvotes: 0

Views: 38

Answers (1)

Paul S.
Paul S.

Reputation: 66404

Let's try it out!

function foo() {
    console.log(this);
}

foo(); // logs window
console.log(foo.hurka); // undefined
foo.blio(); // logs {}
console.log(foo.hurka); // "hurka"

But wait, foo.blio invoked foo!
Therefore, when invoked as foo.blio()

  • this in blio is foo
  • this.apply is equivalent to foo.apply
  • this inside foo was set to {} through the apply

You can read more on Function.prototype.apply on MDN docs here

Upvotes: 2

Related Questions