- You’ve encountered browser API differences or problems — which isn’t really JavaScript’s fault.
- You’re comparing it to a class-based language such as C++, C# or Java — and JavaScript doesn’t behave in the way you expect.
Global Scope
If there’s no current object, ‘this’ refers to the global object. In a web browser, that’s ‘window’ — the top-level object which represents the document, location, history and a few other useful properties and methods.
window.WhoAmI = "I'm the window object";
alert(window.WhoAmI);
alert(this.WhoAmI); // I'm the window object
alert(window === this); // true
Calling a Function
‘this’ remains the global object if you’re calling a function:
window.WhoAmI = "I'm the window object";
function TestThis() {
alert(this.WhoAmI); // I'm the window object
alert(window === this); // true
}
TestThis();
Calling Object Methods
When calling an object constructor or any of its methods, ‘this’ refers to the instance of the object — much like any class-based language:
window.WhoAmI = "I'm the window object";
function Test() {
this.WhoAmI = "I'm the Test object";
this.Check1 = function() {
alert(this.WhoAmI); // I'm the Test object
};
}
Test.prototype.Check2 = function() {
alert(this.WhoAmI); // I'm the Test object
};
var t = new Test();
t.Check1();
t.Check2();
Using Call or Apply
In essence, call and apply run JavaScript functions as if they were methods of another object. A simple example demonstrates it further:
function SetType(type) {
this.WhoAmI = "I'm the "+type+" object";
}
var newObject = {};
SetType.call(newObject, "newObject");
alert(newObject.WhoAmI); // I'm the newObject object
var new2 = {};
SetType.apply(new2, ["new2"]);
alert(new2.WhoAmI); // I'm the new2 object
The only difference is that ‘call’ expects a discrete number of parameters while ‘apply’ can be passed an array of parameters.
That’s ‘this’ in a nutshell! However, there are several gotchas which may catch you out. We’ll discuss those in my next post…
Frequently Asked Questions about ‘this’ in JavaScript
What is the ‘this’ keyword in JavaScript and why is it important?
The ‘this’ keyword in JavaScript is a special keyword that refers to the context in which a function is called. It’s a reference to the object that the function is a method of. The value of ‘this’ is determined by how a function is called. It’s important because it allows you to access the properties and methods of the object within the function, making your code more flexible and reusable.
How does the ‘this’ keyword work in different contexts?
The value of ‘this’ can change depending on the context in which it’s used. In a method, ‘this’ refers to the owner object. Alone, ‘this’ refers to the global object. In a function, ‘this’ refers to the global object. In an event, ‘this’ refers to the element that received the event.
Can you explain how ‘this’ works in event handlers?
In event handlers, ‘this’ refers to the HTML element that received the event. This allows you to directly access and manipulate the element within the event handler function. For example, if you have a button with an onclick event, ‘this’ within the onclick function would refer to the button element.
How does ‘this’ behave in arrow functions?
Arrow functions handle ‘this’ differently than regular functions. In arrow functions, ‘this’ is lexically bound. This means it uses ‘this’ from the code that contains the arrow function. So, for arrow functions, ‘this’ retains the value of the enclosing lexical context’s ‘this’.
What is the difference between ‘this’ in JavaScript and ‘this’ in other programming languages?
In many object-oriented programming languages, ‘this’ always refers to the instance of the current class. However, in JavaScript, the value of ‘this’ is determined by the execution context and how the function is called, not by where the function is defined.
How can I change the context of ‘this’ in a function?
You can change the context of ‘this’ using methods like call(), apply(), and bind(). The call() and apply() methods call a function with a given ‘this’ value and arguments. The difference between the two is that call() accepts an argument list, while apply() accepts a single array of arguments. The bind() method returns a new function, allowing you to bind a function to a specific object.
What is the ‘this’ value in a constructor function?
In a constructor function, ‘this’ refers to the newly created object. When you use the ‘new’ keyword to create an instance of an object, ‘this’ is automatically set to the new object.
How does ‘this’ behave in strict mode?
In strict mode, the value of ‘this’ remains at whatever it was set to when entering the execution context. If it’s not defined, it remains undefined. This is different from non-strict mode where ‘this’ defaults to the global object if not defined.
Can ‘this’ be null or undefined?
Yes, ‘this’ can be null or undefined, especially when working in strict mode or when a function is called with undefined or null as the first argument using call() or apply().
What is the global object in JavaScript?
The global object in JavaScript varies depending on the environment. In a web browser, the global object is the window object. In Node.js, the global object is a global object literal. When ‘this’ is used outside of any function or method, it refers to the global object.
Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he's been advocating standards, accessibility, and best-practice HTML5 techniques. He's created enterprise specifications, websites and online applications for companies and organisations including the UK Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He's written more than 1,000 articles for SitePoint and you can find him @craigbuckler.