Javascript 'this'
Q: What is the result of the following code?
var fullname = 'John Doe';
var obj = {
fullname: 'Colin Ihrig',
prop: {
fullname: 'Aurelio De Rosa',
getFullname: function () {
return this.fullname;
},
},
};
console.log(obj.prop.getFullname()); // $: Aurelio De Rosa
var test = obj.prop.getFullname;
console.log(test()); // $: John Doe
- context of
this
is dependent on how a function is invoked, not how it’s defined - first
console.log()
,getFullname()
is invoked as a function of theobj.prop
object- thus the context refers to
obj.prop
and the function returns theobj.prop.fullname
- thus the context refers to
- second
getFullname()
is assigned to the test variable- thus the context refers to the global window object and the function returns the
window.fullname
- thus the context refers to the global window object and the function returns the
Javascript Call and Apply
What is the difference between .call() and .apply()?
Both call()
and apply()
call a function with a given this
value as the first argument
- The call() method accepts arguments individually
example.call(newContext, "arg1","arg2");
- The apply() method accepts arguments as an array
example.apply(newContext, ["arg1","arg2"]);
call() and apply()
Fix the previous question’s issue so the last console.log() prints Aurelio De Rosa.
// ...code from above... //
console.log(test.call(obj.prop)); // $: Aurelio De Rosa
console.log(test.apply(obj.prop)); // $: Aurelio De Rosa
- forcing the context of the function using either call() or apply()
- in this case using call() or apply() would produce the same result
- main difference is how they accept arguments
- call() requires arguments to be specified separately
example.call(newContext, "arg1","arg2");
- apply() takes arguments as an array
example.apply(newContext, ["arg1","arg2"]);
- call() requires arguments to be specified separately