2011-03-25 28 views
3
創建對象

我瞭解到,您可以通過這種方式創建自己的「類」:問題有關的JavaScript

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"); 

現在,如果foofoo2都需要調用一個名爲foo3另一個函數,我應該在哪裏將它添加到?
我不想foo3wong2被調用,所以我不能只用

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

但是,如果我在全球範圍內定義它,我不認爲這是非常好的。有什麼建議麼?

+1

你能否解釋一下「我不想讓foo3被wong2調用」?我認爲整個觀點是,foo3()將會被當然是wong2的Person的方法調用。 – 2011-03-25 12:59:42

+0

@Ernest'wong2.foo1()'和'wong2.foo2()'可以調用'foo3',但沒有'wong2.foo3',我可以這樣做嗎? – wong2 2011-03-25 13:02:37

回答

4

可以定義foo1和foo2的訪問封閉內foo3,像

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

    ... 

}(); 
0

不知道這是不是你正在尋找,但這是一個靜態函數。

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

爲什麼不創建自己的命名空間?嘗試

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 
0

我得到你想要的東西就像一個靜態函數,其中foo3屬於Person的印象,但不是wong2,當然不是全球範圍。

如果是這樣,只需將函數分配給Person.foo3,如下所示。

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 

如果你想關閉直通一個「私人」成員,那麼這是一個完全不同的動物。

+0

不,我想要一個'私人'成員...無論如何 – wong2 2011-03-25 13:16:41