Home >Web Front-end >JS Tutorial >Why Use \'var self = this\' in JavaScript?

Why Use \'var self = this\' in JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-11-27 02:11:10670browse

Why Use

JavaScript Idiom: Understanding "var self = this"

The "var self = this;" idiom is commonly seen in JavaScript code, particularly in event handlers. It allows you to maintain a reference to the original "this" object within nested functions or within event handler closures.

When you define a function inside a constructor or object, the execution context changes, and "this" refers to the global object (window) in non-strict mode. In strict mode, "this" will be undefined. To avoid this, developers use "var self = this" to preserve the reference to the original object.

Why Use "var self = this"?

Consider the following example from WebKit's HTML5 SQL Storage Notes Demo:

function Note() {
  var self = this;

  var note = document.createElement('div');
  note.className = 'note';
  note.addEventListener('mousedown', function(e) { return self.onMouseDown(e) }, false);
  note.addEventListener('click', function() { return self.onNoteClick() }, false);
  this.note = note;
  // ...
}

In this code, "self" is assigned to "this" within the constructor. This ensures that when the event handlers are invoked (e.g. clicking the 'note' div), "this" will still refer to the original Note object, allowing methods like "onMouseDown" to be called correctly.

Is "var self = this" Commonplace?

Yes, this idiom is widely used in JavaScript applications, particularly when dealing with closures and event handlers. It allows developers to maintain a reference to the original context within nested functions.

Alternative Approach

While "var self = this" is effective, it can be confusing to read. An alternative approach is to use arrow functions (introduced in ES6), which preserve the "this" binding of the surrounding context.

For example:

function Note() {
  var note = document.createElement('div');
  note.className = 'note';
  note.addEventListener('mousedown', (e) => { this.onMouseDown(e) });
  note.addEventListener('click', () => { this.onNoteClick() });
  this.note = note;
  // ...
}

Note:

It is now discouraged to use "var self = this" as it can potentially cause errors due to the existence of "window.self". It is recommended to use arrow functions or other alternatives to maintain "this" binding.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn