Can some one explain this behavior
Asked
Active
Viewed 75 times
-12

Arijit Sil
- 29
- 4
-
5Kindly post your code not image, refer to this [ask]. – Prabhjot Singh Kainth Nov 29 '19 at 06:01
-
Does this answer your question? [Losing "this" context in JavaScript when passing around members](https://stackoverflow.com/questions/30486345/losing-this-context-in-javascript-when-passing-around-members) – Sebastian Simon Oct 11 '20 at 18:56
1 Answers
0
This is due to the behavior of the "this" keyword on the different contexts where it's been used.
So here is the complete reference for this keyword
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
var foo = {
bar : function(){
console.log(this); // For your reference
return this.baz;
},
baz: 1
};
(function(v){
console.log(typeof arguments[0]()); // In this context "this" keyword refers to the current function "bar" and not the parent foo object, As the current function doesn't contain baz it returns undefined
console.log(typeof foo.bar()); // In this context "this" keyword refers to its parent "foo" Object so this.baz will be refer to foo.baz and typeof 1 is a number
console.log(typeof v()); // Here "this" keyword refers to the window object hence this.baz will refer to window.baz which is undefined
return typeof arguments[0]();
})(foo.bar);

Community
- 1
- 1

Senthur Athiban
- 136
- 5