JavaScript: private, public, static methods and properties

JavaScript has its own way to define scoping of variables, properties and methods. Public properties and methods are declared with this.property1 and this.method1() in a function F1 (class). And all the var   declared variables are private and also as usual functions (function f1(), function f2() etc.) are private method.  You can add private, public and static methods as follows:


//constructor function (class)
function Maths(x, y) {
//public properties
this.x =x;
this.y = y;

//public methods
this.add = function () { _sum = x + y; return _sum; }
this.mod = function () { _mod = x % y; return _mod; }

//public method calls private method
this.show = function () {
this.add();
this.mod();
showResult();
}

//private variables
var _sum=0;
var _mod=0;

//private methods
function showResult() {
alert( "sum: " + _sum + ", mod: " + _mod );
}

}
//end function

//create instance
var plus = new Maths(3, 4);
plus.show();

//static method multiply, you can use it without instance of Maths
Maths.multiply = function (x,y) {  return x * y; }

//call static method by constructor function (class) without instance of Maths
var result = Maths.multiply(5,7);
alert(result);
//output: 35

Advertisements

About M Moniruzzaman
A passionate software engineer, have been developing applications on various platforms such as Android, iPhone, .Net (C#) technologies and web based ASP.NET, PHP, JavaScript, jQuery technologies for more than 10 years. Especially I have expertise on developing applications for Android and iPhone, as well as service oriented, client-server based applications where clients will be reside on Android/iPhone that communicate with WCF(.NET) service hosted on server. I have completed certification in Microsoft Certified Professional Developer (MCPD) on .Net 4 . I have completed my graduation in -- B.Sc. (Engineering) in Computer Science and Engineering, ShahJalal University of Science and Technology, Bangladesh. Thanks, M. Moniruzzaman (Zaman)

One Response to JavaScript: private, public, static methods and properties

  1. tanvir ahmed says:

    sneha is a dream

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: