3

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?

wong2
  • 34,358
  • 48
  • 134
  • 179
  • 1
    Can you explain "I don't want foo3 to be called by wong2" ? I thought the whole point was that foo3() is going to be called by the methods of Person which, of course, wong2 has. – Ernest Friedman-Hill Mar 25 '11 at 12:59
  • @Ernest `wong2.foo1()` and `wong2.foo2()` can call `foo3`, but no `wong2.foo3`, can I do this? – wong2 Mar 25 '11 at 13:02

5 Answers5

4

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

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

    ...

}();
Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186
2

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

Community
  • 1
  • 1
yojimbo87
  • 65,684
  • 25
  • 123
  • 131
0

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
}
Han Dijk
  • 1,602
  • 1
  • 14
  • 20
0

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
Alistair Laing
  • 983
  • 1
  • 7
  • 18
0

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.

jon_darkstar
  • 16,398
  • 7
  • 29
  • 37