This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 6 years ago.
Could somebody here please get this straight for all of us once and for all?
var parent = {child: function(){
console.log(this);
var log = function(){
console.log(this);};
log();
}
}
When I call parent.child()
I get:
Object{}
Window{}
Other people/ documentation on Mozilla say that this function has been invoked without any context. And
this
will be the object on which the function is invoked.
What I don't understand is how on earth this function within another object is considered to be without a context(so this defaulted to the global object). What's the logic here? Thanks
Function referenced at objects are like methods. When you directly call a function by indexing an object, this same object will be referenced by this in the scope the function will generate.
When calling a function without indexing an object, or without setting this context (with apply, bind, call, ...), if it's not at strict mode (or is at least in a global scope when at strict mode) this should be the global object.
When objects are instances of classes/interfaces/functions, their methods also capture this same object for this.
This is how it works for me:
(function() {
'use strict'
console.log(this) // undefined
})()
console.log(this) // Window{}
Related
This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 8 years ago.
// example A (works)
foo(function() {
myObj.save();
});
// example B (doesn't work)
foo(myObj.save);
// example C (works)
foo(myObj.save.bind(myObj));
Why is the this reference correct when myObj.save is called in example A, but not in example B?
I can force this to be correct by using bind, but what is happening in example A that is different from example B?
I don't understand why this would be different.
Functions only have a context, this, when invoked.
When you call x.y(), the this context inside y is x.
When you write x.y, you're referencing just the function y, you're not invoking it and there is no context. When you pass that function elsewhere, such as z = x.y, the context is not passed with it.
You're doing that in your second example. You're passing the function without context into foo, where there is no possible way for foo to know what the context should be. When it's invoked by foo, it's going to be invoked a simple save() call, and when this happens the this context will be window (or null in strict mode).
This is because this refers to the object on which a method was called. When you set the method of a function to a variable, or pass it in as an argument, it is no longer associated with the object it was a method of.
Multiple objects can share the same function, this is a way of dynamically reusing that function to manipulate the object instance it is a method of.
The bind method was added later to address use cases such as these.
This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 8 years ago.
I am learning javascript but I have some doubts about functions/closures, i have this code:
var obj = { value: 0 };
obj.test = function() {
var that = this;
var f1 = function() {
console.log(that);
};
f1();
};
obj.test();
var x = obj.test;
x();
I know that when a function is invoked like f() this refer to the global object but in my example when f1 is defined it has a reference that to the this of the outer function that refer to obj.
I expect that the function remember the context in which it was created so why the last call x() refers to the global object?
Thanks
I expect that the function remember the context in which it was created
That right there is your mistake. JavaScript functions do not "remember" any relationship to any particular object in a case like that. The only things they remember are in-scope variables in the chain of parent lexical contexts. In this case, the "obj" variable is such a variable.
You can explicitly create a function that remembers a relationship to an object with the .bind() method.
obj.boundTest = obj.test.bind(obj);
var x = obj.boundTest;
x(); // will do the right thing
or even more simply:
var x = obj.test.bind(obj);
x();
I expect that the function remember the context in which it was created
It doesn't.
Context is determined by how a function is called and only by how a function is called.
You are calling it in the global context, so this is the global object.
The reason for this occurring is that when you make a copy of that function
var x = obj.test;
you are only copying the function. Not the object, nor any of its variables. So when you attempt to run x (which is obj.test) it runs fresh. The result is that this is re-evaluated which now refers to the global context (or undefined in strict mode).
This question already has answers here:
Reason behind this self invoking anonymous function variant
(5 answers)
Closed 8 years ago.
Is there a particular reason why i often encounter:
(function() {
console.log("Hello");
}).call(this);
instead of:
(function() {
console.log("Hello");
})();
It should have the same effect when passing this to call or not?
There seems to be some performance difference: http://jsperf.com/call-vs-parenthesis.
Presumably the code within that function uses this (where you just have console.log). In the version with call, this within the function is the same as this outside it. Without call, this inside the function is either the global object (loose mode) or undefined (strict mode).
If you're not using this within the function, there's no reason to be doing the call version, and I would lean toward not doing so because it's additional unnecessary complexity (and apparently a very very small performance cost).
The addition of .call(this) is important, it changes the context of the function enclosure, meaning that the this keyword will refer to the same this as the outer function enclosure.
In your particular code it doesn't make any difference because inside your function you do not refer to this at all.
this.a = 123;
(function() {
console.log(this.a); // always 123 regardless of scope
}).call(this);
That is significant assuming that this refers to something other than the window object. If this is already pointing to the window, then adding .call(this) makes no difference, since without it, by default the this will go to the window.
This question already has answers here:
What does "return this" do within a javascript function?
(4 answers)
Closed 6 years ago.
Function.prototype.method = function (name, func) {
this.prototype[name] = func;
return this;
};
Stolen from Crockford's Good Parts. When the code returns 'this', what does 'this' reference in this case?
I always ask myself this when I see 'this' inside a js code because I know that js is funky with the word this (i.e. 'this' actually references the global variable when it is used inside a nested function)
As you are extending Function.prototype, this will refer to a function instance.
Example:
function foo() {};
foo.method(); // `this` refers to foo
There are like four different ways of calling functions, which determine what this refers to. MDN has a good article about it.
In short:
Simple function call: Global object (window in browsers)
Object method: The object (i.e. obj.method(), this references obj) (that's the case we have in your example)
Using the new keyword: An empty object, inheriting from the functions prototype
call / apply: Whatever you pass as first argument
In this context, this is a reference to the Function Instance.
this refers to the constructor Function that calls it's method method. So for example you can do this:
function Car(color){
this.color = color || 'blue';
}
Car.method('showcolor',function(){return this.color;});
//^Car is a constructor function, so 'this' in 'method' refers to Car here
var redcar = new Car('red'), yellowcar = new Car('yellow');
alert(redcar.showcolor()); //=> red
alert(yellowcar.showcolor()); //=> ... you guessed it!
This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
'this' keyword, not clear
this operator in javascript
function foo()
{
if(this === window)
return null;
return 1;
}
var i = foo(); // returns 1;
What is the this member of a global function, and how can I test from within a function if it's being called in a global scope or as a member function?
Edit: It seems JQuery makes a difference here, since everybody assures me foo should return null for run-of-the-mill JavaScript. How does JQuery change this?
Note that the OP says, in a comment, below, that this is in a Greasemonkey script.
According to this the difference is because of greasemonkey (not JQuery).
A Greasemonkey user script, however, by default wraps up all code inside an anonymous function wrapper that swallows identifiers, causing them not to end up on the global object.
It goes on to say that you can use #unwrap to make this point to the window as it does with regular on-page Javascript.
this refers to the window object in this case.
Just do alert(this); and it will say [object Window]
But if you do
var i = new foo(); // returns an object (instance of foo);
then this refers to the instance of foo.
The this member refers to the entire page, and will always be defined - your foo() method will never return null.
this always points on the current element. In the case of foo(), this points to window.