Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to set var self = this; from outside the function?
    primarykey
    data
    text
    <p>I have a class-like function</p> <pre><code>var myapp = function() { this.method = function() { //Do something... } } </code></pre> <p>To reference <code>myapp</code> from within methods, the first line in the <code>myapp</code> function is</p> <pre><code>var self = this; </code></pre> <p>So a method in <code>myapp</code> can reference the "class" safely</p> <pre><code>this.anothermethod = function() { self.method(); } </code></pre> <p>The full code:</p> <pre><code>var myapp = function() { var self = this; this.dosomething = function(Callback) { Callback(); } this.anothermethod = function() { //Pass a callback ("self" is required here)... this.dosomething(function() { self.complete(); )}; } this.complete = function() { console.log('All done!'); } } </code></pre> <p><strong>My question is</strong>: can I assign <code>var self = this;</code> from <em>outside</em> the declaration of <code>myapp</code>? I don't want to set <code>self</code> every single time I write a "class".</p> <p>Kind of like this:</p> <pre><code>var library = function() { this.loadclass = function(Name) { var tempclass = window[Name]; library[Name] = new tempclass(); library[Name].self = library[Name]; } } var myapp = new library(); myapp.loadclass('myapp'); myapp.myapp.dosomething(); </code></pre> <p>It doesn't work as expected. <code>self</code> equals <code>window</code> for some reason.</p> <p>I know it's a little abnormal programming, but can it be done?</p> <hr> <p>Note about using <code>self</code>: I remember why I started using it. I wanted to reference the base class (<code>this</code>) from within callbacks inside methods. As soon as you try to use <code>this</code> within a function within a method, it then references the method, not the base class.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload