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…
Use
thisinstead ofself. self will not be accessible toinitializefunction as it is defined outside the scope ofklass selfBest option is define
selfinside each function as last solution I provided.OR
OR