2009-07-14 2 views
1

Ich möchte das Function-Objekt erweitern, um beim Erstellen eines neuen Objekts mehr Operationen auszuführen.
Ist es möglich?Kann ich während der Objektkonstruktion Aktionen ausführen, indem ich den Prototyp der Funktion modifiziere?

+1

Sie gehen zu müssen, für mehr Details oder Ihre Frage geschlossen werden, um. –

+0

Es klingt, als ob Sie den Prototyp der Funktion modifizieren möchten, so dass Sie jederzeit Code ausführen können, wenn ein Objekt aus einer Funktion konstruiert wird ... Geht es um den Kern davon? – Prestaul

+0

@ Prestaul: Ja. –

Antwort

2

Es gibt keine Möglichkeit, den Funktionsprototyp zu ändern, sodass Sie Aufrufe an eine Funktion abfangen können. Der nächste Schritt, den Sie damit erreichen, ist das Hinzufügen einer Methode, die Sie anstelle eines Konstruktors aufrufen können. Zum Beispiel:

Function.prototype.create = function() { 
    var obj = new this(); // instantiate the object 
    this.apply(obj, arguments); // call the constructor 

    // do your stuff here (e.g. add properties or whatever it is you wanted to do) 
    obj.foo = 'bar'; 

    return obj; 
}; 

function SomeObject(name) { 
    this.name = name; 
} 

var obj = SomeObject.create('Bob'); 
obj.foo; // => 'bar' 

Alternativ könnten Sie eine Funktion schreiben, die Sie nennen würde einen Konstruktor bauen:

Function.makeConstructor = function(fn) { 
    return function proxyConstructor() { 
     // check to see if they called the function with the "new" operator 
     if(this instanceof proxyConstructor) { 
      var obj = new fn(); 
      fn.apply(obj, arguments); 

      // do your stuff here (e.g. add properties or whatever it is you wanted to do) 
      obj.foo = 'bar'; 

      return obj; 
     } else { 
      return fn.apply(null, arguments); 
     } 
    }; 
}; 

var SomeObject = Function.makeConstructor(function(name) { 
    this.name = name; 
}); 

var obj = SomeObject.create('Bob'); 
obj.foo; // => 'bar' 
+0

Kannst du nicht einfach ein Event veranstalten? –

+0

Es gibt kein Ereignis, das ausgelöst wird, wenn Sie einen Objektkonstruktor aufrufen. Das JavaScript-Objektmodell ist nicht mit der DOM-API verknüpft, in der sich das Browserereignismodell befindet. Ich denke wirklich, dass dies so nah ist, wie du es bekommen wirst. – Prestaul