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

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.

Related

Lexical `this` and Timeout [duplicate]

This question already has answers here:
How does the "this" keyword in Javascript act within an object literal? [duplicate]
(4 answers)
Closed 5 years ago.
Im reading through the YDKJS books and I thought I understood lexical this for the most part.
However there is a section with code that shows this:
var obj = {
id: "awesome",
cool: function coolFn() {
console.log( this.id );
}
};
var id = "not awesome";
obj.cool(); // awesome
setTimeout( obj.cool, 100 ); // not awesome
Ok so the first obj.cool() makes sense of course....but why is the setTimeout printing not awesome.....I mean it's still calling obj.cool() which this refers to it's own objects id?
Or does setTimeout get called as another function that calls obj.cool()? but even in that case (Which I tried calling obj.cool() inside another function that also had an id property and it still printed the right one......so why would the this change with setTimeout?
Since the OBJ.COOL function is passed by reference, you are not actually passing the context object with it. The function gets new invocation context and executes on the WINDOW object, which now has a property called ID which was defined earlier.

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

Javascript this keyword inside functions [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.
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();

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

Why does "this" gets different values? [duplicate]

This question already has answers here:
How does the "this" keyword in Javascript act within an object literal? [duplicate]
(4 answers)
Maintaining the value of 'this' when using event listener
(2 answers)
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 9 years ago.
var foo = {
data: "a",
print: function() {console.log(this.data)}
}
element.addEventListener("click", function(){foo.print()});
In this case context is foo object
element.addEventListener("click", foo.print);
When in this one it's element
Why is it so?
The value of this is determined by the way a function is called. In the first case, the "print" function is called via a property reference from the object "foo". Therefore, the value of this is a reference to that object.
In the second case, you've passed the reference to the "print" function to the system when setting up the event handler. Event handlers are invoked with this set to refer to the element involved in the event.
In your first example, the value of this in the anonymous function will also be a reference to the clicked element. You could transmit that to the "print" function if you wanted to:
element.addEventListener("click", function(){ foo.print.call(this); });
When you say
foo.print
you will be getting a reference to the function, but the function is actually attached to foo object which is lost by passing the foo.print. So, print becomes an unbound function. You can confirm this like this.
var a = foo.print;
a(); // `this` will be referring to global now
To avoid this, you should bind the function with the object, like this
element.addEventListener("click", foo.print.bind(foo));
Now we are making sure that the function is bound to the foo object. You can check this, like this
var a = foo.print.bind(foo);
a(); // a

Categories