JavaScript: Qué son.extender y.prototipo utilizado para?


Soy relativamente nuevo en JavaScript y sigo viendo .extender y .prototipo en bibliotecas de terceros que estoy usando. Pensé que tenía que ver con el prototipo de la biblioteca javascript, pero estoy empezando a pensar que no es el caso. ¿Para qué se utilizan?

Author: cdeszaq, 2010-09-23

5 answers

La herencia de Javascript se basa en prototipos, por lo que se extienden los prototipos de objetos como la Fecha, las matemáticas e incluso los propios personalizados.

Date.prototype.lol = function() {
 alert('hi');
};

( new Date ).lol() // alert message

En el fragmento de código anterior, defino un método para todos los objetos de fecha (ya existentes y todos los nuevos ).

extend es generalmente una función de alto nivel que copia el prototipo de una nueva subclase que desea extender de la clase base.

Así que puedes hacer algo como:

extend( Fighter, Human )

Y el Fighter el constructor / objeto heredará el prototipo de Human, por lo que si define métodos como live y die en Human, entonces Fighter también los heredará.

Aclaración actualizada:

Significado de" función de alto nivel".extend no está incorporado, pero a menudo lo proporciona una biblioteca como jQuery o Prototype.

 123
Author: meder omuraliev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-19 00:04:29

.extend() es añadido por muchas bibliotecas de terceros para facilitar la creación de objetos a partir de otros objetos. Véase http://api.jquery.com/jQuery.extend / o http://www.prototypejs.org/api/object/extend para algunos ejemplos.

.prototype se refiere a la" plantilla " (si desea llamarlo así) de un objeto, por lo que al agregar métodos al prototipo de un objeto (esto se ve mucho en las bibliotecas para agregar a String, Date, Math o incluso Function) esos métodos se agregan a cada nueva instancia de ese objeto.

 22
Author: pnomolos,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-09-23 18:29:48

El método extend por ejemplo en jQuery o PrototypeJS, copia todas las propiedades del objeto de origen al objeto de destino.

Ahora acerca de la propiedad prototype, es un miembro de objetos de función, es parte del núcleo del lenguaje.

Cualquier función se puede utilizar como constructor, para crear nuevas instancias de objetos. Todas las funciones tienen esta propiedad prototype.

Cuando se utiliza el operador new con en un objeto de función, un nuevo objeto ser creado, y heredará de su constructor prototype.

Por ejemplo:

function Foo () {
}
Foo.prototype.bar = true;

var foo = new Foo();

foo.bar; // true
foo instanceof Foo; // true
Foo.prototype.isPrototypeOf(foo); // true
 18
Author: CMS,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-09-23 18:33:23

La herencia de Javascript parece ser como un debate abierto en todas partes. Se puede llamar "El curioso caso del lenguaje Javascript".

La idea es que haya una clase base y luego extienda la clase base para obtener una característica similar a la herencia (no completamente, pero aún así).

La idea es entender lo que realmente significa prototipo. No lo entendí hasta que vi el código de John Resig (cerca de lo que hace jQuery.extend) escribió un fragmento de código que lo hace y afirma que base2 y prototype las bibliotecas fueron la fuente de inspiración.

Aquí está el código.

    /* Simple JavaScript Inheritance
     * By John Resig http://ejohn.org/
     * MIT Licensed.
     */  
     // Inspired by base2 and Prototype
    (function(){
  var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;

  // The base Class implementation (does nothing)
  this.Class = function(){};

  // Create a new Class that inherits from this class
  Class.extend = function(prop) {
    var _super = this.prototype;

    // Instantiate a base class (but only create the instance,
    // don't run the init constructor)
    initializing = true;
    var prototype = new this();
    initializing = false;

    // Copy the properties over onto the new prototype
    for (var name in prop) {
      // Check if we're overwriting an existing function
      prototype[name] = typeof prop[name] == "function" &&
        typeof _super[name] == "function" && fnTest.test(prop[name]) ?
        (function(name, fn){
          return function() {
            var tmp = this._super;

            // Add a new ._super() method that is the same method
            // but on the super-class
            this._super = _super[name];

            // The method only need to be bound temporarily, so we
            // remove it when we're done executing
            var ret = fn.apply(this, arguments);        
            this._super = tmp;

            return ret;
          };
        })(name, prop[name]) :
        prop[name];
    }

    // The dummy class constructor
    function Class() {
      // All construction is actually done in the init method
      if ( !initializing && this.init )
        this.init.apply(this, arguments);
    }

    // Populate our constructed prototype object
    Class.prototype = prototype;

    // Enforce the constructor to be what we expect
    Class.prototype.constructor = Class;

    // And make this class extendable
    Class.extend = arguments.callee;

    return Class;
  };
})();

Hay tres partes que están haciendo el trabajo. Primero, recorre las propiedades y añádelas a la instancia. Después de eso, se crea un constructor para que más tarde se agregue al objeto.Ahora, las líneas clave son:

// Populate our constructed prototype object
Class.prototype = prototype;

// Enforce the constructor to be what we expect
Class.prototype.constructor = Class;

Primero apunta el Class.prototype al prototipo deseado. Ahora, todo el objeto ha cambiado, lo que significa que debe forzar el diseño a su propio diseño.

Y el uso ejemplo:

var Car = Class.Extend({
  setColor: function(clr){
    color = clr;
  }
});

var volvo = Car.Extend({
   getColor: function () {
      return color;
   }
});

Lea más al respecto aquí en Javascript Inheritance por el mensaje de John Resig.

 16
Author: ambodi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-12 10:37:36

Algunas funciones de extend en bibliotecas de terceros son más complejas que otras. Knockout.js por ejemplo, contiene uno mínimamente simple que no tiene algunas de las comprobaciones que tiene jQuery:

function extend(target, source) {
    if (source) {
        for(var prop in source) {
            if(source.hasOwnProperty(prop)) {
                target[prop] = source[prop];
            }
        }
    }
    return target;
}
 1
Author: Simon_Weaver,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-14 07:00:48