I have searched for a way of defining a class in javascript like in java or php but I found none!
I want something like
class javascriptClass {
function someFunction(){}
}
I have searched for a way of defining a class in javascript like in java or php but I found none!
I want something like
class javascriptClass {
function someFunction(){}
}
You can use a prototype class, like so:
function MyClass() {
}
MyClass.prototype.method1 = function() {
// do stuff
};
MyClass.prototype.method2 = function(p) {
// do stuff
};
var myClass = new MyClass();
Now, after instantiating an object myClass from the prototype MyClass, you can access the methods of the object myClass:
myClass.method1();
The above method is great if you need to instantiate more than one object/instance of the class.
If you only expect to have one object, then another method you can use simply acts as a namespace to protect your functions from collisions with others:
var myObject = {
method1: function() {
// do stuff
},
method2: function(p) {
// do stuff
}
};
myObject.method1();
In JavaScript, you don't have classes as such. You define functions that are used to create objects with new
, and you can give them methods by either creating them in the body of the constructor, or adding them through the object's prototype. For example:
function JavaScriptClass() {
// I am a JavaScript constructor! Any initialization can be done here.
}
// This is the prototype! You can put instance methods and variables (to an extent) here.
JavaScriptClass.prototype.someFunction = function() {
alert('someFunction was called!');
};
// Now, let's create an instance!
var obj = new JavaScriptClass();
obj.someFunction(); // someFunction was called!
And you can access the current object using this
, in both the constructor and any methods bound to the object. Note that this
can also be bound to just about anything in JavaScript. It's a different type of OOP.
Unlike class-based languages, JavaScript is functional languages or prototypal language, you can't use class
keyword or the kind of signature you have posted in JavaScript. In JavaScript, normally you would do:
function Person(){
// public members
this.foo = 'foo';
this.walk = function(){ ......... }
// private members
var bar = 'bar';
var baz = function(){.........}
}
var person = new Person();