chris clarke
software development that works…or something
Private, Public and Static in JavaScript
September 22, 2007 on 4:30 pm | In JavaScript |JavaScript doesn’t have keywords for making things private, public or static like other languages but it is possible - unfortunately like most things in JavaScript it’s possible in several different ways!
Public and private access in JavaScript
To declare a method public in JavaScript you can assign it to the prototype:
// The class
Monkey = function () {};
// The public method getBananas
Monkey.prototype.getBananas = function() { ... };
..or you can also assign it to this in the constructor:
Monkey = function () {
this.getBananas = function () { ... };
};
To make things private you can take different approaches aswell. You can just define them to a var in the constructor:
Monkey = function () {
var privateMethod = function () { ... };
};
…or you can use the approach Carlos Villela suggests and define your public and private methods in different objects inside the constructor and return the public object:
Monkey = function() {
var private = {
privateMethod : function () { ... }
};
var public = {
getBananas : function () { ... }
};
return public;
}();
Static members in JavaScript
Static members are easy, you just define them directly on the class:
Monkey.MAX_BANANAS = 120;
Monkey.swingFromTree = function () { ... }
No Comments yet »
RSS feed for comments on this post. TrackBack URI
Leave a comment
Private, Public and Static in JavaScript
September 22, 2007 on 4:30 pm | In JavaScript |JavaScript doesn’t have keywords for making things private, public or static like other languages but it is possible - unfortunately like most things in JavaScript it’s possible in several different ways!
Public and private access in JavaScript
To declare a method public in JavaScript you can assign it to the prototype:
// The class
Monkey = function () {};
// The public method getBananas
Monkey.prototype.getBananas = function() { ... };
..or you can also assign it to this in the constructor:
Monkey = function () {
this.getBananas = function () { ... };
};
To make things private you can take different approaches aswell. You can just define them to a var in the constructor:
Monkey = function () {
var privateMethod = function () { ... };
};
…or you can use the approach Carlos Villela suggests and define your public and private methods in different objects inside the constructor and return the public object:
Monkey = function() {
var private = {
privateMethod : function () { ... }
};
var public = {
getBananas : function () { ... }
};
return public;
}();
Static members in JavaScript
Static members are easy, you just define them directly on the class:
Monkey.MAX_BANANAS = 120;
Monkey.swingFromTree = function () { ... }
No Comments yet »
RSS feed for comments on this post. TrackBack URI
Leave a comment
Powered by Cheese.
RSS Entries Feed.
RSS Comments Feed
^Top^