Javascript this keyword inside functions [duplicate] - javascript

This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 6 years ago.
I am trying to understand internals of Javascript. I have some misunderstanding of this keyword.
Everywhere stated that this keyword is reference to the object that invokes function.
But as far as I know function is an object as well.
So consider this example
var car = {
brand: "Nissan",
getBrand: function(){
var closure = function(){
console.log(this.brand);
console.log(this);
};
return closure();
}
};
car.getBrand();
Why does this reference inside closure point to the global object instead of getBrand wrapping function ? Again everything is object in javascript, so I cannot understand this behavior.
Please explain this from internals perspective.
Thanks

Because value of this is determined by how function is called..closure is called with no reference of context and global context is window(in Browser)
Use Function.prototype.call to specify this context while function is invoked
var car = {
brand: "Nissan",
getBrand: function() {
var closure = function() {
console.log(this.brand);
console.log(this);
};
return closure.call(this);
}
};
car.getBrand();

Related

Why is 'this' in JavaScript refer to different context in the examples? [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?
(14 answers)
scope of the object literal methods
(3 answers)
Closed 4 years ago.
I am quite new to JavaScript, I am really confused by the below two examples of 'this', on what 'this' is bound to and why:
Example 1:
function Person(age) {
this.age = age;
this.growOld = () => {
this.age++;
}
}
var person = new Person(1);
setTimeout(person.growOld,1000);
Example 2:
var Actor = {
name: 'RajiniKanth',
movies: ['Kabali', 'Sivaji', 'Baba'],
getName: () => {
alert(this.name);
}
};
Actor.getName();
Why even though both examples use arrow function, but 'this' is bound to different context?
A method inside an object using an arrow function this will bind to the object, if if not inside an object this refers to the global scope, even if encapsulated by another method.
The keyword this has different meanings in function expressions and function declarations.
Arrow functions are expressions. Accordingly, this is bound to a lexical context.
See MDN this

"This" keyword does refer the current object with lamda [duplicate]

This question already has an answer here:
Arrow functions return this as the window object
(1 answer)
Closed 5 years ago.
Consider this code:
var obj = {
method : function(){
console.log( this ); // This prints the **obj** correctly
}
};
And the same code with Lambda:
var obj = {
method : () => {
console.log( this ); // This prints **Window** object
};
};
Why are the outputs different?
The ES6 arrow function syntax uses “lexical scoping” to figure out what the value of “this” should be. Lexical scoping is fancy way of saying it uses “this” from the surrounding code… the code that contains the code in question, hence it is
window
here.

Why "this" is not working? [duplicate]

This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 6 years ago.
In java script when we make a new constructor function we use "this.property name". We use "this" to refer the object which currently in use. But in a general function we doesn't use "this" keyword. According to my understanding if we use "this" in function it should point to the current function. However when we used, it was not producing the expected result. Why? Example
function greet(name){ console.log("Hello " + this.name);
}
Output is "Hello" then blank.
Because in general function, we are by default referring 'window' object so anything we make it becomes window level object or variable.
Like,
function fun(){
this.title = "window";
}
fun();
or window.fun(); //both are same. Since we call window.fun, this.title means window.fun.
If you create like this:
var obj = {
}
**Now to make title at obj level, you can do like this:
fun.call(obj);
Now you can call obj.title.**
Read this about this
In most cases, the value of this is determined by how a function is called.
When you use the new keyword in javascript an implicit object is created and returned from the function call. Inside of the function this refers to the newly created object. Calling a function without new does not have the same behavior.
See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new

Inconsistent scope of 'this' in javascript [duplicate]

This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 7 years ago.
In javascript all functions are objects. So how come when I use 'this' like so:
var myObj = function() {
doSomething: function() {
alert('msg');
}
myFunc2: function () {
this.doSomething(); //'this' doesn't equal myFunc2, it's myObj
}
}
'this' refers to myObj and not myFunc2? Javascript has function scope, 'this' is being used in myFunc2 so it should refer to myFunc2.
Why is this not the case? This language seems very inconsistent at times.
JavaScript doesn't have "function scope", what you are experimenting the how the this works in JavaScript.
The this keyword always reference the object that is calling the function, in this case, myObj.
Check this chapter from the You Don't Know JS book series to learn more about how this works in JavaScript:
You Don't Know JS: this & Object Prototypes

How does 'this' works in javascript? [duplicate]

This question already has answers here:
In Javascript, why is the "this" operator inconsistent?
(8 answers)
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 9 years ago.
hi i am a little confusion on how exactly this works in javascript.Based on this example:
var myFunction = function(){
function testMe(){
console.log(this) --------> DOMwindow
}
console.log(this) ---------> myFunction
}
var myvariable = new myFunction();
What is happening here?
The value this references depends on circumstances. Any unscoped (i.e. not in an object) function call will have this = window (DOMWindow, if you prefer). Anything that is part of a prototype, or has been changed using apply or bind, will have this as that object ("itself", if you prefer).
So, to illustrate. When you are instantiating using the new keyword, your function automatically inherits this as itself. When you call an IETF within it, this within this IETF will point to the global scope.
If you would like to avoid this, instead of calling testMe literally, you can always do this:
var myFunction = function() {
var testMe = function() {
console.log(this);
}
testMe.bind(this);
}
Which will, in turn, have this within testMe use the object as it should.

Categories