2012-02-12 19 views
9

¿Cómo heredo/extiendo las clases que usan el patrón Revelar prototipo? ¿Y hay alguna manera de hacer que las variables private y las funciones protected?¿Cómo implementar la herencia en JS Revelando el patrón prototipo?

Ejemplo objeto base:

myNameSpace.Person = function() { 

    this.name= ""; 
    this.id = 0; 

}; 

myNameSpace.Person.prototype = function(){ 
    var foo = function(){ 
     //sample private function 
    }; 
    var loadFromJSON = function (p_jsonObject) { 
     ... 
    }; 
    var toJSON = function() { 
     ... 
    }; 
    var clone = function (p_other) { 
     ... 
    }; 

    return { 
     loadFromJSON : loadFromJSON, 
     toJSON: toJSON, 
     clone: clone 
    }; 
}(); 

Respuesta

7

No hay protegidas variables/propiedades en JavaScript. Sin embargo, puede reutilizar variables "privadas" cuando declara las clases heredadas en el mismo ámbito, lo que parece posible en su caso cuando las variables privadas son solo "utilidades ocultas" de su prototipo.

MyNamespace.Person = function Person(params) { 
    // private variables and functions, individual for each Person instance 
    var anything, id; 
    function execute_something() {} 

    // public properties: 
    this.name = ""; 
    this.getId = function getId(){ 
     // called a "privileged function", because it has access to private variables 
    } 
} 
MyNamespace.American = function(params) { 
    MyNamespace.Person.call(this, params); // inherit name and getId() 
} 

(function() { // new scope for 
    // hidden utility functions and other private things 
    function foo() { } 
    function helpJSON() { } 
    function fromJSON() { } 
    var bar; 

    (function(personProto) { // new scope for prototype module (not explicitly needed) 
     // "private" /static/ variables (and functions, if you want them private) 
     var personCount = 0; 

     personProto.clone = function clone() { 
      return this.constructor(myself); // or something 
     }; 
     personProto.toJSON = function toJSON() { 
      // use of helpJSON() 
     }; 
     personProto.fromJSON = fromJSON; // direct use 
    })(MyNamespace.Person.prototype); 

    (function(amiProto) { 
     // just the same as above, if needed 
     amiProto.special = function() { 
      // use foo() and co 
     }; 
    })(MyNamespace.American.prototype = Object.create(MyNamespace.Person.prototype)); 
})(); 

Ésta es la forma de herencia JavaScript, lo que significa prototipo de American hereda las funciones clone(), toJSON() y fromJSON (automágicamente) desde el prototipo de la persona. Por supuesto sobrescribible. Y la característica es

new MyNamespace.American() instanceof MyNamespace.Person; // true 

Por supuesto, si usted no necesita eso, y quiere utilizar el módulo de forma más similar, se puede volver a utilizar las funciones de utilidad, es decir, sólo tiene que copiarlos:

(function() { 
    // hidden utility functions and other private things 
    var bar; 
    var personCount; 
    function foo() { } 
    function helpJSON() { } 
    function fromJSON() { } 
    function clone() { 
     return this.constructor(myself); // or something 
    } 
    function toJSON() { } 

    (function(personProto) { // new scope, not really needed 
     // private variables are useless in here 
     personProto.clone = clone; 
     personProto.toJSON = toJSON; 
     personProto.fromJSON = fromJSON; 
    })(MyNamespace.Person.prototype); 

    (function(amiProto) { // new scope, not really needed 
     // copied from personProto 
     amiProto.clone = clone; 
     amiProto.toJSON = toJSON; 
     amiProto.fromJSON = fromJSON; 
     // and now the differences 
     amiProto.special = function() { 
      // use foo() and co 
     }; 
    })(MyNamespace.American.prototype); 
})(); 
+1

Si desea obtener más información sobre la herencia y el prototipo, hay una gran lectura aquí: http://killdream.github.com/blog/2011/10/understanding-javascript-oop/index.html Creo que puede ir a punto 3 donde comienza la herencia. –

+0

Desafortunadamente ese enlace da un error 404 ahora. –

+1

@Programmer_D: Se movió a http://robotlolita.me/2011/10/09/understanding-javascript-oop.html. Y, por supuesto, también puede [ver la versión anterior] (http://web.archive.org/web/20130127102509/http://killdream.github.com/blog/2011/10/understanding-javascript-oop/index .html) – Bergi

Cuestiones relacionadas