What is the "this" pointer for global functions? [duplicate] - javascript

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.

Related

Function Context in Javascript and this Keyword [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.
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{}

Declare variable so that would be it visible in global context but not belong to window or gett

I need to emulate in firefox the behavior of activeXobject in last versions of ie. I write addon with contentScript and want to implement to pages such variable. It is exactly what I want - It is a challenge in itself.
Example of IE 11 working code:
if (window.ActiveXObject == undefined) {
var but = new window.ActiveXObject; // [ActiveXObject object]
}
I need exactly same behavior in firefox with my variable
For example what i want
<script>
console.log(window.variable) // undefined
console.log(new window.variable); // [object Variable]
console.log(new variable) // [object Variable] if not possible previous string
</script>
for solving, you can change the addon sdk or a browser source, change realization of all getters or something else
In browser Javascript, there is no such thing as a global variable that is not a property of the window object. So, if that's truly what you are trying to do, then it cannot be done. Yes, you might be able to create a getter on the window object with Object.defineProperty(), but that's still a property on the window object so I'm not sure how that helps you.
Likewise, there is no structure in Javascript such that:
window.ActiveXObject === undefined
and this works:
var x = new window.ActiveXObject;
Javascript just simply doesn't work that way. The property either exists or it doesn't. It can't be undefined for one way of accessing it and defined for some other way of accessing it.
You might also be able to create the property on the window object so it is not enumerable if you want it to be less visible for some reason.
If you explained what you're really trying to accomplish, there may be some work-arounds by enclosing the relevant code in a closure and defining the variable in the closure, but without knowing more details about what the actual problem to be solved is, we can't help more specifically than that.
If you just want the variable defined for YOUR code only, then you can just put it in a closure:
(function() {
var myVar = "foo";
// other parts of your code
// elsewhere in your code
console.log(myVar);
})();
Your code can treat it like a global, but it's really not a global, it's just defined within the scope that your code lives and not available to any other code outside this scope.
Theoretically, this is possible with lexically declared variables in ES6:
let variable = 5;
console.log(variable); // 5
console.log(window.variable) // undefined
However, the current let support in FF is not as advanced, and still treats this a property of the global object.
If the variable only needs to be accessible by your project code, wrap all of your project code in a self executing anonymous function.
(function(){
var internalGlobalVar = "some value";
//All your code gets wrapped in here...
})();
Then if you tried to alert(window.internalGlobalVar) you would get undefined.
We use google closure compiler with plovr and wrap all of our code in a self executing anonymous function so basically all of our global variables are project scope, not on the window "output-wrapper": "(function($){%output%})(jQuery);"

Why is .call(this) used instead of parenthesis [duplicate]

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.

Why does this refer to window or object based on where parenthesis are placed? And return undefined

I am working on flexible javascript widget. In the course of some testing, I noticed that the context of this changes based on whether the parenthesis used to call a function are placed inside an object or in the global context of its call. Why do the parenthesis matter? And why would parenthesis inside the object refer to window and when placed in global context refer to the object. It seems like it would be the other way around.
Also undefined is returned in both instances. Is there a way to execute the function without returning anything?
I feel like I'm missing something important about this and don't want to miss out.
//this refers to window
var dataSource = {
read: read()
};
function read(){
console.log(this);
}
dataSource.read;
//this refers to dataSource object
var dataSource = {
read: read
};
function read(){
console.log(this);
}
dataSource.read();
Your code is doing two different things.
The first example is executing read() as the object definition is executed (read() is available because it's a function declaration and is hoisted, though this isn't related to the problem you're experiencing). It is called without any context so its this is window (as per the specification, where window is the browser's global object).
The second example has a reference to read(), which is then executed at the end of the block. Because it's executed as a property of dataSource, its this will become that. However, if you first assigned that reference to somewhere else and then invoked it via that reference, you'd again lose that this context.
For fine-grained control of this, take a look at bind(), call() and apply().
Also undefined is returned in both instances. Is there a way to execute the function without returning anything?
A function always has a return value (undefined if not explicitly set), but you're free to ignore it.
The scoping of this can be a tricky topic in javascript. That said, I can expand my answer on the general rules regarding the scope of this if need be.
But to answer your specific question, whenever you reference this inside an object literal, it by default, refers to the object literal itself.
Edit: as long as the function was invoked as a property of the object literal.
Where as, almost in any other situation I can call to mind, this will refer to the window object unless specified when invoking said function using apply() or call().
When this is used outside of objects it refers to the global object which in browser environment is window. Otherwise it refers to the last bareword before the last dot in the invocation.
For example:
function foo () {return this};
var bin = {bar:{foo:foo},foo:foo};
foo(); // returns window
bin.foo(); // returns bin
bin.bar.foo(); // returns bar
// ^
// |
// '------ last bareword before the last dot in the invocation
Now, as to why the location of the parenthesis matter. I think you should be able to guess by now:
When we add a parenthesis to a word (variable/name/reference) what we're doing is make a function call:
foo(); // call foo
If we don't add the parenthesis, what we're doing is refer to the object:
foo; // this contains the function foo
Note that not adding the parens is not calling the function. Therefore it should be obvious that when you do:
var bar = { foofoo : foo() }
What you're doing is passing the result of the function foo to bar.foofoo. The function is invoked without any "dots" in its invocation path. Therefore it doesn't belong to any object and therefore the rule of this == window applies.
On the other hand if you do:
var bar = { foo : foo }
What you're doing is assign the function foo to bar.foo. When you later call it as:
bar.foo()
the invocation contains a "dot" therefore the rule about the last object before the last dot applies.
See my previous answer to a related question for a detailed explanation on how this works in javascript: How does the "this" keyword in Javascript act within an object literal?

What is the context of a function in an array?

This is something that I'm sure I should know the answer to, but either I'm just being stupid or I've just somehow never come across this before...
Given the following array, declared in the global scope:
var arr = [function() {
console.dir(this);
}];
I would have expected this to refer to the Window object. However, when calling the function:
arr[0]();​ //Logs Array
It appears that this actually refers to the array. Then, when I store a reference to the function in another variable and call that, this does refer to the Window object:
var func = arr[0];
func(); //Logs Window
So, why does the context of the function change? Here's a fiddle demonstrating the above two cases.
When you call a function as property of an object, such as obj.func(), this refers to obj.
This is exactly what you are doing here. arr is your object and 0 is the property holding a function.
Note: After all, arrays are just objects and their elements are the values of their properties (though properties are typically numerical strings (all properties are strings)).
See MDN - this for more information, in this case:
When a function is called as a method of an object, its this is set to the object the method is called on.
In your second case, you call the function "standalone", hence this refers to window. If the code was run in strict mode though, this would be undefined.
This is because this keyword is actually an operator which returns the reference to the holder (or owner) of a function where it was called. Since in first case the holder is an array (which is an object) it returns an array. In the second case the holder is the window object.
See this article for more details.
be noted:
in JavaScript, this always refers to the function owner.
you can read more about it at quirksmode.
Because the element is a member of the array, and this always points to the owner object (unless you play with bind()/ call()/ apply() etc). If you're not part of an object, this will be the global object; which is window in the browser environment. The exception to this is if you're in strict mode, where this will be undefined.
What you're doing is effectively the same as:
var ar = {
'0' : function () {
console.dir(this);
}
}
ar[0]();
var func = ar[0];
func();
... which may make more sense conceptually.
http://jsfiddle.net/TVtwr/1/

Categories

Resources