this variable depends (resolves) based on invocation/execution context (and not where it is defined).
this refers to object which has called the method.
6 ways of invoking a function/method
Regular function (without Object qualifier)- In
browser, default object wouldwindowif strict mode is off andundefinedif strict mode is on. - In
node, default object would beglobalobject.
e.g.
fun(); // Its equivalent to window.fun()
- In
Constructor functionwith new keyword e.g.var obj = new fun();
Object methodAssociation of the function stays even after invocationvar val = 1; var myObj = { val : 2, someFunction : function() { console.log(this.val); } }; myObj.someFunction();
IIFE(Immediately Invoked Function Expression) /Self Invoking functionvalue of this is always equal towindowobject. e.g.IIFE is self invoked, it has not been called by any object. Hence, the value of this inside IIFE is Window object.(function fun(){ /* body */ }());
- Use
call()function with invocation target and params valuescomma separated.
e.g.fn.call(object, varargs….)No long term associationsum.call(emp, 1, 2);
- Use
apply()function with invocation target and param values in anarray.
e.g.fn.apply(object, array of values)No long term association
sum.apply(emp, [1,2]);
Variables are passed
- this - Invocation context, who calls this
- arguments
- length
- name
- caller
Functions are provided by javascript
- apply
- call
- bind
- toString
- Symbol