Understanding the JavaScript Idiom: var self = this
In JavaScript, you may encounter the idiom 'var self = this' in certain scenarios. To understand its purpose, let's consider the example from the WebKit HTML 5 SQL Storage Notes Demo:
function Note() { var self = this; // ... }
Maintaining Context
In this example, 'self' is used to preserve a reference to the original 'this' context, even when the context changes within nested functions. Event handlers often employ this technique, especially in closures.
By assigning 'this' to 'self', when inner functions are called, they can still access the original 'this' context, which is crucial for accessing instance properties and methods.
Alternative Naming
It's worth noting that the name 'self' is merely a convention. Alternative names like 'that' are equally valid. The key is to establish a variable that maintains the original 'this' reference.
Function Scope
Functions declared within a context can access variables and functions defined in that scope or in outer scopes. This principle applies to nested functions and closures as well.
Example
Consider the following event callback:
function MyConstructor(options) { let that = this; // ... document.addEventListener('click', (event) => { alert(that.someprop); }); }
In this example, 'that' preserves the context of 'MyConstructor'. The click event handler can now access the instance property 'someprop' of the object created with 'MyConstructor'.
The above is the detailed content of Why Use `var self = this` in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!