objeto new herencia es6 ejemplos create crear javascript object inheritance object-create

new - Herencia de JavaScript con Object.create()?



new object javascript (7)

¿Cómo heredo con Object.create ()? Intenté estos, pero ninguno está funcionando:

var B = function() {}; var A = function() {}; A = Object.create(B); A.prototype.C = function() {};

y

var B = function() {}; var A = function() {}; A.prototype.C = function() {}; A = Object.create(B);

y

var B = function() {}; A = Object.create(B); var A = function() {}; A.prototype.C = function() {};

Nada funcionó. ¿Cómo se supone que debo usar esta nueva función Object.create () -?


El patrón que utilizo para esto es ajustar cada tipo en un módulo y exponer las propiedades de create y prototype , así:

var Vehicle = (function(){ var exports = {}; exports.prototype = {}; exports.prototype.init = function() { this.mph = 5; }; exports.prototype.go = function() { console.log("Going " + this.mph.toString() + " mph."); }; exports.create = function() { var ret = Object.create(exports.prototype); ret.init(); return ret; }; return exports; })();

Entonces puedo construir tipos derivados así:

var Car = (function () { var exports = {}; exports.prototype = Object.create(Vehicle.prototype); exports.prototype.init = function() { Vehicle.prototype.init.apply(this, arguments); this.wheels = 4; }; exports.create = function() { var ret = Object.create(exports.prototype); ret.init(); return ret; }; return exports; })();

con este patrón, cada tipo tiene su propia función create() .


La documentación original para Douglas ''Object.create está aquí http://javascript.crockford.com/prototypal.html . Asegúrese de haber incluido la definición del método

if (typeof Object.create !== ''function'') { Object.create = function (o) { function F() {} F.prototype = o; return new F(); }; }


Puede definir Object.create usted mismo, pero si no es nativo tendrá que lidiar con que se enumere en cada bucle for in que utiliza para los objetos.

Hasta ahora, solo nuevos webkits: Safari5 y Chrome lo admiten de forma nativa.



Object.create() se usa para heredar objetos, no constructores como lo que intentas hacer. Más o menos crea un nuevo objeto con el antiguo conjunto de objetos como su padre prototipo.

var A = function() { }; A.prototype.x = 10; A.prototype.say = function() { alert(this.x) }; var a = new A(); a.say(); //alerts 10 var b = Object.create(a); b.say(); //alerts 10 b.x = ''hello''; b.say(); //alerts ''hello''

Y solo para asegurarnos de que b no sea solo un clon de a,

a.x = ''goodbye''; delete b.x; b.say(); //alerts ''goodbye''


Hay varias formas de hacer herencia en JavaScript

Herencia de construcción. Utilizado si no necesita llamar al constructor supertipo:

function Rectangle(length, width) { this.length = length; this.width = width; } Rectangle.prototype.getArea = function() { return this.length * this.width; }; // inherits from Rectangle function Square(size) { this.length = size; this.width = size; } Square.prototype = Object.create(Rectangle.prototype); var rect = new Rectangle(6, 8); var square = new Square(10); console.log(rect.getArea()); // 48 console.log(square.getArea()); // 100 console.log(rect instanceof Rectangle); // true console.log(rect instanceof Object); // true console.log(square instanceof Square); // true console.log(square instanceof Rectangle); // true console.log(square instanceof Object); // true

Constructor Robando. Se usa si es necesario llamar al constructor supertipo:

function Rectangle(length, width) { this.length = length; this.width = width; } Rectangle.prototype.getArea = function() { return this.length * this.width; }; // inherits from Rectangle function Square(size) { Rectangle.call(this, size, size); } Square.prototype = Object.create(Rectangle.prototype); var rect = new Rectangle(6, 8); var square = new Square(10); console.log(rect.getArea()); // 48 console.log(square.getArea()); // 100 console.log(rect instanceof Rectangle); // true console.log(rect instanceof Object); // true console.log(square instanceof Square); // true console.log(square instanceof Rectangle); // true console.log(square instanceof Object); // true


Bueno, es años tarde, pero para cualquier otra persona tropezar con esto. Puedes usar Object.assign en FF y Chrome.

En este ejemplo, cuando el cubo se está creando con create. Primero Object.create (this) crea el objeto con la propiedad z, luego con Object.assign (obj, Square.create (x, y)) llamará a Square.create y lo devolverá y anexará a Cube que está siendo almacenado en obj .

var Square = { x: 0, y: 0, create: function(x,y) { var obj = Object.create(this); obj.x = x; obj.y = y; return obj; } }; var Cube = { z: 0, create:function(x,y,z) { var obj = Object.create(this); Object.assign(obj, Square.create(x,y)); // assign(target,sources...) obj.z = z; return obj; } }; // Your code var MyCube = Cube.create(20,30,40); console.log(MyCube);