wong2
wong2

Reputation: 35750

Question about create object in JavaScript

I've learned that you can create your own 'class' in this way:

function Person(name, age){
    this.name = name;
    this.age  = age;
}

Person.prototype.foo = function(){
    // do something
}

Person.prototype.foo2 = function(){
    // do something
}

var wong2 = new Person("wong2", "20");

Now if foo and foo2 both need to call another function named foo3, where should I add it to?
I don't want foo3 to be called by wong2, so I can't just use

Person.prototype.foo3 = function(){
    // something else else
}

But if I define it in the global scope, I don't think it's very nice. Any suggestions?

Upvotes: 2

Views: 115

Answers (5)

jon_darkstar
jon_darkstar

Reputation: 16788

I get the impression you want something like a static function, where foo3 belongs to Person, but not to wong2 and certainly not to the global scope.

If so, just assign a function to Person.foo3 as i have below.

http://jsfiddle.net/audLd/1/

function Person(name, age){
    this.name = name;
    this.age  = age;       
}

Person.foo3 = function() {return 10;};

Person.prototype.foo = function(){
    return Person.foo3();
}

Person.prototype.foo2 = function(){
    return Person.foo3()*2;
}

var wong2 = new Person("wong2", "20");

alert("" + wong2.foo() + ", " + wong2.foo2()); //works

alert("" + Person.foo3()); //works.  this is the distinction between what I'm loosely calling static and private

alert(foo3()); //doesnt work
alert(wong2.foo3()); //doesnt work

If you want a 'private' member thru closures then that is an entirely different animal.

Upvotes: 0

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81724

You can define foo3 inside a closure that foo1 and foo2 have access to, something like

function() {
    function foo3() { ... }
    Person.prototype.foo = function(){
       foo3();
    }

    ...

}();

Upvotes: 3

Alistair Laing
Alistair Laing

Reputation: 973

why not create your own namespace? try

var person = {}; 
person.createPerson=function (name,age){
   this.name=name; 
   this.age=age; 
   if (age<18){
     this.status = 'cannot Marry';
   }else{
     person.addMarriageStatus('married');
   }
}
person.addMarriageStatus = function(status){this.status=status};
person.createPerson('Jack',2);
//person

Upvotes: 0

Han Dijk
Han Dijk

Reputation: 1612

Don't know if this is exactly what you are looking for, but this acts as a static function.

Person.foo3 = function() {
    // something else else else but not inherited by wong2
}

Upvotes: 0

yojimbo87
yojimbo87

Reputation: 68403

Try to look at this SO question and article about Private Members in JavaScript.

Upvotes: 1

Related Questions