user2039981
user2039981

Reputation:

Javascript - this vs window

If you can, if the code is not invoked in a function, should you use this instead of window?

this.addEventListener(...);

vs

window.addEventListener(...);

this is 2 chars shorter, is it better to use if you can?

Upvotes: 1

Views: 2558

Answers (5)

Trace
Trace

Reputation: 18869

In the environment of a web browser, thisrefers to the Window object, if no other context is given.
Using Window would make it less dubious, so I would go with Window if necessary.

Note that it is always good practice to add eventlisteners to the smallest possible context for performance reasons.
If only a part of the DOM needs to listen for events, there is no need to add an eventlistener in the browser global scope.

Aside from an event listener on the body element for removing eg. popup windows, I never added eventlisteners to the Window object before.

Upvotes: 0

Stan Shaw
Stan Shaw

Reputation: 3034

This refers to the parent of whatever code block you're currently inside. If the code is inside a click event, 'this' refers to the control that invoked the event. If the code is run on page load, 'this' refers to the browser window. Using 'window' makes it more apparent to what you're referring and makes the code more readable.

Upvotes: 0

Jared Smith
Jared Smith

Reputation: 21926

I recommend avoid 'this' unless its explicitly specified via call, apply, or bind. That way there's never any question about what this refers to. And I'm also fond of always explicitly declaring access to a global object:

(function(global, document, undefined){
    global.myGlobalVar = 'foo';
})(window, document);

This way it is always clear when I'm doing anything global, the code can be more easily ported to a non-browser environment like node.js, undefined will always be undefined, etc.

If you don't make your global access explicit and have to try to find it later, you will regret it. If you're registering an event handler globally (probably not the best idea) you definitely want to make note of it.

EDIT: Should probably mention that in strict mode this is undefined in the global scope.

Upvotes: 4

Emmanuel Delay
Emmanuel Delay

Reputation: 3679

What ever arguments you are looking for; typing two characters more or less is not it.

this and window are different things.
'window' is the whole web page. 'this' depends on the function you are in.

Upvotes: 0

nmarsh
nmarsh

Reputation: 164

this and window are not the same thing. Depending on context, this can refer to any number of elements, while window always means window.

see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this for more info

Upvotes: 2

Related Questions