Olaf Schneider: Zugriff aus privater Methode in Prototype-Objekt auf this?

Beitrag lesen

Hallo,

• Step 1: Ich habe ein Objekt Foo, dessen Konstruktorfunktion ich eine id übergeben kann. Die Methode getId() gibt mir die id zurück.

  
var Foo = function(id) {  
    this.getId = function() {  
        return id;  
    }  
}  
  
myFoo = new Foo(23);  
alert(myFoo.getId()); // -> 23  

-> klappt prima.

• Step 2: Foo soll weitere Funktionalität erhalten, die ich über das Prototyp-Objekt von Foo zur Verfügung stelle:

  
var Foo = function(id) {  
    this.getId = function() {  
        return id;  
    }  
}  
  
Foo.prototype = new function() {  
    this.getSpecialId = function() {  
        return this.getId() + 1;  
    }  
    this.showSpecialId = function() {  
        alert(this.getSpecialId());  
    }  
}  
  
myFoo = new Foo(23);  
myFoo.showSpecialId(); // -> 24  

-> klappt auch prima.

• Step 3: Jetzt habe ich folgende Überlegung: Ich möchte gerne, dass nicht alle Methoden öffentlich sind, z.B. getSpecialId() soll privat sein. Mein erster Gedanke war, genau so zu verfahren, als stände sämtlicher Code in der Konstruktor-Funktion und nicht im Prototype-Objekt:

  
var Foo = function(id) {  
    this.getId = function() {  
        return id;  
    }  
}  
  
Foo.prototype = new function() {  
    var that = this;  
    var getSpecialId = function() {  
        return that.getId() + 1;  
    }  
    this.showSpecialId = function() {  
        alert(getSpecialId());  
    }  
}  
  
myFoo = new Foo(23);  
myFoo.showSpecialId(); // -> Fehler 'that.getId is not a function'  

Allerdings bezieht sich jetzt wohl „that“ in getSpecialId() ausschließlich auf Foo.prototype und Foo ist ihm völlig unbekannt. Daher bricht das Script mit einem Fehler ab, da die Methode getId() unbekannt ist.

Ist es möglich, in privaten Methoden innerhalb von Foo.prototype auf Methoden oder Eigenschaften von Foo zuzugreifen?

Gruß
Olaf