What underlies this JavaScript idiom: var self = this?

javascript self object
javascript self = this pattern
javascript self equivalent
const self = this
javascript assign this to self
var self this bind
this variable in javascript
javascript this

I saw the following in the source for WebKit HTML 5 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;
  // ...
}

The author uses self in some places (the function body) and this in other places (the bodies of functions defined in the argument list of methods). What's going on? Now that I've noticed it once, will I start seeing it everywhere?

See this article on alistapart.com. (Ed: The article has been updated since originally linked)

self is being used to maintain a reference to the original this even as the context is changing. It's a technique often used in event handlers (especially in closures).

Edit: Note that using self is now discouraged as window.self exists and has the potential to cause errors if you are not careful.

What you call the variable doesn't particularly matter. var that = this; is fine, but there's nothing magic about the name.

Functions declared inside a context (e.g. callbacks, closures) will have access to the variables/function declared in the same scope or above.

For example, a simple event callback:

function MyConstructor(options) {
  let that = this;

  this.someprop = options.someprop || 'defaultprop';

  document.addEventListener('click', (event) => {
    alert(that.someprop);
  });
}

new MyConstructor({
  someprop: "Hello World"
});

What underlies this JavaScript idiom: var self = this?, What underlies this JavaScript idiom: var self = this? Find to do, but could be dangerous because there is a window.self - see also: Window.self. var o = {f: function() { return this.a + this.b; }}; var p = Object.create(o); p.a = 1; p.b = 4; console.log(p.f()); // 5 In this example, the object assigned to the variable p doesn't have its own f property, it inherits it from its prototype.

I think the variable name 'self' should not be used this way anymore, since modern browsers provide a global variable self pointing to the global object of either a normal window or a WebWorker.

To avoid confusion and potential conflicts, you can write var thiz = this or var that = this instead.

Javascript var self = this; vs. .bind · GitHub, When I started JavaScript I used to see this code a lot of time and I always wondered why do I need to assign this to another variable and then  en fait self est une référence à window ( window.self) donc quand vous dites var self = 'something' vous outrepassez une référence de window à elle - même-parce que self existe dans l'objet window. C'est pourquoi la plupart des développeurs préfèrent var that = this plutôt que var self = this;

Yes, you'll see it everywhere. It's often that = this;.

See how self is used inside functions called by events? Those would have their own context, so self is used to hold the this that came into Note().

The reason self is still available to the functions, even though they can only execute after the Note() function has finished executing, is that inner functions get the context of the outer function due to closure.

JavaScript : why 'var self = this' - Vijay Shekhawat, var self = this $('#foobar').bind('click', function(){ self. This question is not specific to jQuery, but specific to JavaScript in general. scope What underlies this JavaScript idiom var self = this · Difference between this and self in JavaScript  To work around the different meaning of this in nested functions such as DOM event handlers, it is a common idiom in JavaScript to save the this reference of the calling object in a variable (commonly called that or self), and then use the variable to refer to the calling object in nested functions.

It should also be noted there is an alternative Proxy pattern for maintaining a reference to the original this in a callback if you dislike the var self = this idiom.

As a function can be called with a given context by using function.apply or function.call, you can write a wrapper that returns a function that calls your function with apply or call using the given context. See jQuery's proxy function for an implementation of this pattern. Here is an example of using it:

var wrappedFunc = $.proxy(this.myFunc, this);

wrappedFunc can then be called and will have your version of this as the context.

javascript - var self = this?, var w1 = window; var w2 = self; var w3 = window.window; var w4 Recommendation, First snapshot containing the definition of Window.self . so if the button named 'somename1' calls the function, the variable 'name' will be assigned to 'somename1' and so if 'somename2' called it, it will be assigned to 'somename2' javascript jquery reference this

As others have explained, var self = this; allows code in a closure to refer back to the parent scope.

However, it's now 2018 and ES6 is widely supported by all major web browsers. The var self = this; idiom isn't quite as essential as it once was.

It's now possible to avoid var self = this; through the use of arrow functions.

In instances where we would have used var self = this:

function test() {
    var self = this;
    this.hello = "world";
    document.getElementById("test_btn").addEventListener("click", function() {
        console.log(self.hello); // logs "world"
    });
};

We can now use an arrow function without var self = this:

function test() {
    this.hello = "world";
    document.getElementById("test_btn").addEventListener("click", () => {
        console.log(this.hello); // logs "world"
    });
};

Arrow functions do not have their own this and simply assume the enclosing scope.

Window.self, What's the point of assigning this to the self variable? Why not just use this ? I'm just wondering if this is a stylistic preference or is their some underlying value  where 'oldre' is the original regexp that I want to insert a variable, 'xx' is the placeholder for that variable/alias/function, and 'yy' is the actual variable name, alias, or function.

Why do developers use self? : javascript, demonstrate in the Chrome JavaScript console that if you enter "window" and /​962033/what-underlies-this-javascript-idiom-var-self-this - after showing how to  An arrow function expression is a syntactically compact alternative to a regular function expression, although without its own bindings to the this, arguments, super, or new.target keywords. Arrow function expressions are ill suited as methods, and they cannot be used as constructors.

mcguffin-javascript, A mostly reasonable approach to JavaScript. 2.1 Use const for all of your references; avoid using var . eslint: prefer-const , no-const- If you find that a function's definition is large or complex enough that it is 9.4 It's okay to write a custom toString() method, just make sure it works successfully and causes no side effects. The phenotypic differences between individual organisms can often be ascribed to underlying genetic and environmental variation. However, even genetically identical organisms in homogeneous environments vary, indicating that randomness in developmental processes such as gene expression may also generate diversity.

Airbnb JavaScript Style Guide, JavaScript is very dynamic and relies on “prototypal inheritance,” which is a significantly different paradigm than class-based inheritance. Such distinctions do not immediately relate to binding issues, but demonstrate that traditional object-related syntaxes and behaviors were of little importance to the designers of JavaScript.

Comments
  • This is a JS language feature called "lexical closure."
  • Possible duplicate of: var self = this?.
  • the concept of THIS is explained explicitly here scotch.io/@alZami/understanding-this-in-javascript
  • Relevant example in this answer stackoverflow.com/a/20279485/5610569 (to the question "How to access the correct this inside a callback?")
  • Appears that article morphed into using var that = this;
  • @BobStein Thanks. I'll update the answer accordingly.
  • I usually use _this
  • @djheru +1. so much nicer than "that" (which my brain will never get used to).
  • I started using "me" :)
  • Until modern browsers start providing a global variable _this, that, or me.
  • There's absolutely no problem with using the name self as long as you declare it as a variable, it'll shadow the global. Of course if you forgot the var then it wouldn't work with any other name either.
  • For me the cogent point is that self has no special meaning. I personally prefer using a var named something other than self since it frequently confuses me, as I expect 'self' to be a reserved word. So I like your answer. And in the example of the OP, I'd prefer var thisNote = this or similar.
  • @steve agreed, although I try to avoid using this/self references in general as they are very brittle in terms of maintainability.