简体   繁体   中英

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?

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

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

    ...

}();

尝试在JavaScript中查看有关私有成员的 这个问题和文章。

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
}

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM