Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference self in a new javascript function?

I am trying to make a "Class" factory with Javascript so that I can create different types of objects.

Here is the function I'm using:

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;    
};

Then I can do:

var myObject = Class({
    initialize: function() { console.log(self);}
});
var createdObject = new myObject();

However, the console.log(self) is always referring to Window, and I'd like it to refer to the object itself.

I know this is a scope issue, but I'm confused on how to create a reference to the object?

I am trying to make a "Class" factory with Javascript so that I can create different types of objects.

Here is the function I'm using:

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;    

};

Then I can do:

var myObject = Class({
    initialize: function() { console.log(self);}
});
var createdObject = new myObject();

However, the console.log(self) is always referring to Window, and I'd like it to refer to the object itself.

I know this is a scope issue, but I'm confused on how to create a reference to the object?

For example, if I wanted to do:

var myObject = Class({
    initialize: function() { 
       $('#myDiv').click( function() {
           self.anotherFunction();
       });
    },

    anotherFunction: function() {
        alert('hi');
    }
});

I would need to be able to reference the "myObject" with self...

like image 597
johnnietheblack Avatar asked Aug 27 '26 23:08

johnnietheblack


1 Answers

Use this instead of self. self will not be accessible to initialize function as it is defined outside the scope of klass self

Best option is define self inside each function as last solution I provided.

var myObject = Class({
    initialize: function() { console.log(this);}
});

OR

 var myObject = Class({
        initialize: function() { console.log(createdObject);}
    });

OR

var myObject = Class({
            initialize: function() { var self = this; console.log(self );}
        });
like image 121
Anoop Avatar answered Aug 30 '26 12:08

Anoop