Creating classed in JavaScript
Posted
by Renso
on Geeks with Blogs
See other posts from Geeks with Blogs
or by Renso
Published on Mon, 01 Oct 2012 10:40:41 GMT
Indexed on
2012/10/01
21:39 UTC
Read the original article
Hit count: 255
Filed under:
Goal:
Creating class instances in JavaScript is not available since you define "classes" in js with object literals. In order to create classical classes like you would in c#, ruby, java, etc, with inheritance and instances.
Rather than typical class definitions using object literals, js has a constructor function and the NEW operator that will allow you to new-up a class and optionally provide initial properties to initialize the new object with.
The new operator changes the function's context and behavior of the return statement.
var Person = function(name) {
this.name = name;
};
//Init the person
var dude= new Person("renso");
//Validate the instance
assert(dude instanceof Person);
When a constructor function is called with the new keyword, the context changes from global window to a new and empty context specific to the instance; "this" will refer in this case to the "dude" context.
Here is class pattern that you will need to define your own CLASS emulation library:
var Class = function() {
var _class = function() {
this.init.apply(this, arguments);
};
_class.prototype.init = function(){};
return _class;
}
var Person a new Class();
Person.prototype.init = function() {
};
var person = new Person;
In order for the class emulator to support adding functions and properties to static classes as well as object instances of People, change the emulator:
var Class = function() {
var _class = function() {
this.init.apply(this, arguments);
};
_class.prototype.init = function(){};
_class.fn = _class.prototype;
_class.fn.parent = _class;
//adding class properties
_class.extend = function(obj) {
var extended = obj.extended;
for(var i in obj) {
_class[i] = obj[i];
};
if(extended) extended(_class);
};
//adding new instances
_class.include = function(obj) {
var included = obj.included;
for(var i in obj) {
_class.fn[i] = obj[i];
};
if(included) included(_class);
};
return _class;
}
Now you can use it to create and extend your own object instances:
//adding static functions to the class Person
var Person = new Class();
Person.extend({
find: function(name) {/*....*/},
delete: function(id) {/*....*/},
});
//calling static function find
var person = Person.find('renso');
//adding properties and functions to the class' prototype so that they are available on instances of the class Person
var Person = new Class;
Person.extend({
save: function(name) {/*....*/},
delete: function(id) {/*....*/}
});
var dude = new Person;
//calling instance function
dude.save('renso');
© Geeks with Blogs or respective owner