开发者

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 f开发者_高级运维unction 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();
    }

    ...

}();


Try to look at this SO question and article about Private Members in 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜