Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Creating static methods 1

Status
Not open for further replies.

jasonsalas

IS-IT--Management
Jun 20, 2001
480
GU
I'With the AJAX craze of late I'm doing a lot more OOP-style JavaScript. I'd like to know how to create/call Java/C#-style static methods (shared methods for the VB'ers) in JavaScript. I know how to use prototypes to create methods within defined classes, like so:

// constructor
function Person() {
this.firstName = 'foo';
this.lastName = 'bar';
}

// method
Person.prototype.getName = function() {
return this.firstname + ', ' + this.lastName;
}

...and then instantiate a Person object:
var p = Person();
alert('My Person object: ' + p.getName);

...but I'd like to be able to call methods without having to create instances of the class, like so:

alert(Person.getName());

Basically, what the Math class does. This is easy to do in Java and C#, merely marking any method as 'static'. Thanks for your help!
 
[1]
>...and then instantiate a Person object:
var p = Person();

Should be
[tt]var p = [red]new[/red] Person();[/tt]

[2]
>...but I'd like to be able to call methods without having to create instances of the class, like so:
alert(Person.getName());

The closest to the static "class" is to construct it like this.
[tt]
function Person() {
var x=new Object();
x.firstName="foo";
x.lastName="bar";
return x
}

Person.getName=function() {
return Person().firstName + ', ' + Person().lastName;
}

var p=Person.getName();
alert(p);
var q=Person().firstName;
alert("first name: " + q);
[/tt]
 
Thanks tsuji!

A lot of the constructs I've seen with Prototype and script.aculo.us use something like:

var Person = {
doSomething: function() {
alert('Feigning a static method');
}
}

Person.doSomething();

...I've tried replicating those examples in my own samples, but they never work out. Any suggestions?
 
I don't know. For a naive mind, it is can be this, just a couple of parentheses operator more! but who know...
[tt]
var Person2 = function() {
var x=new Object();
x.firstName="foo";
x.lastName="bar";
x.doSomething=function() {
alert ('Feigning a static method');
}
return x;
}

Person2().doSomething();
var q=Person2().firstName
alert(q);
[/tt]
There, people have a lot of space to play inflation.
 
I've also seen people define multiple methods for the same JavaScript class within a JSON array:

// constructor
function Person() {
this.fname = 'foo';
this.lname = 'bar';
}

Person.prototype = {
method1: function() {},
method2: function() {},
method3: function() {}
}

...OOP in JavaScript can get pretty nutty.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top