Sto cercando di ottenere un oggetto JavaScript per utilizzare le "questo" assegnazioni del costruttore di un altro oggetto, nonché di assumere il prototipo di tutti gli oggetti funzioni. Ecco un esempio di quello che sto cercando di realizzare:La funzione Javascript che utilizza "this =" restituisce "Lato sinistro non valido nell'assegnazione"
/* The base - contains assignments to 'this', and prototype functions
*/
function ObjX(a,b) {
this.$a = a;
this.$b = b;
}
ObjX.prototype.getB() {
return this.$b;
}
function ObjY(a,b,c) {
// here's what I'm thinking should work:
this = ObjX(a, b * 12);
/* and by 'work' I mean ObjY should have the following properties:
* ObjY.$a == a, ObjY.$b == b * 12,
* and ObjY.getB == ObjX.prototype.getB
* ... unfortunately I get the error:
* Uncaught ReferenceError: Invalid left-hand side in assignment
*/
this.$c = c; // just to further distinguish ObjY from ObjX.
}
Sarei grato per i tuoi pensieri su come avere ObjY sussumere le assegnazioni di ObjX a 'questo' (cioè non deve ripetere tutte le this.$* = *
assegnazioni in ObjY's constructor) e ObjY assume ObjX.prototype.
Il mio primo pensiero è quello di provare la seguente:
function ObjY(a,b,c) {
this.prototype = new ObjX(a,b*12);
}
Idealmente mi piacerebbe imparare a fare questo in modo prototipale (cioè non devono utilizzare uno qualsiasi di questi sostituti 'classici' come OOP Base2).
Può essere interessante notare che ObjY sarà anonima (per esempio factory['ObjX'] = function(a,b,c) { this = ObjX(a,b*12); ... }
) - se ho la terminologia giusta.
Grazie.
correlati: [? Perché non è possibile assegnare un nuovo valore a “questo” in un prototipo di funzione] (http: // stackoverflow.com/q/9713323/1048572) – Bergi