Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to reference self in a new javascript function?
    primarykey
    data
    text
    <p>I am trying to make a "Class" factory with Javascript so that I can create different types of objects.</p> <p>Here is the function I'm using:</p> <pre><code>var Class = function(methods) { var klass = function() { var self = this; this.initialize.apply(this, arguments); }; for (var property in methods) { klass.prototype[property] = methods[property]; } if (!klass.prototype.initialize) klass.prototype.initialize = function(){}; return klass; }; </code></pre> <p>Then I can do:</p> <pre><code>var myObject = Class({ initialize: function() { console.log(self);} }); var createdObject = new myObject(); </code></pre> <p>However, the console.log(self) is always referring to Window, and I'd like it to refer to the object itself.</p> <p>I know this is a scope issue, but I'm confused on how to create a reference to the object?</p> <p>I am trying to make a "Class" factory with Javascript so that I can create different types of objects.</p> <p>Here is the function I'm using:</p> <pre><code>var Class = function(methods) { var klass = function() { var self = this; this.initialize.apply(this, arguments); }; for (var property in methods) { klass.prototype[property] = methods[property]; } if (!klass.prototype.initialize) klass.prototype.initialize = function(){}; return klass; </code></pre> <p>};</p> <p>Then I can do:</p> <pre><code>var myObject = Class({ initialize: function() { console.log(self);} }); var createdObject = new myObject(); </code></pre> <p>However, the console.log(self) is always referring to Window, and I'd like it to refer to the object itself.</p> <p>I know this is a scope issue, but I'm confused on how to create a reference to the object?</p> <p>For example, if I wanted to do:</p> <pre><code>var myObject = Class({ initialize: function() { $('#myDiv').click( function() { self.anotherFunction(); }); }, anotherFunction: function() { alert('hi'); } }); </code></pre> <p>I would need to be able to reference the "myObject" with self...</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.
 

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