Наследование JavaScript с помощью Object.create ()? - PullRequest
15 голосов
/ 20 июня 2010

Как мне наследовать с Object.create ()?Я пробовал это, но никто не работает:

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

и

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

и

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

Ничего не работаетКак я должен использовать эту новую функцию Object.create ()?

Ответы [ 7 ]

27 голосов
/ 02 января 2014

Существует несколько способов наследования в JavaScript

Строительное наследование.Используется, если вам не нужно вызывать конструктор супертипа:

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

Воровство конструктора.Используется, если необходимо вызвать конструктор супертипа:

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
22 голосов
/ 20 июня 2010

Object.create() используется для наследования объектов, а не конструкторов, как вы пытаетесь сделать.Он в значительной степени создает новый объект со старым объектом, установленным в качестве родительского прототипа.

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'

И просто для того, чтобы убедиться, что b не просто клон a,

a.x = 'goodbye';
delete b.x;
b.say(); //alerts 'goodbye'
16 голосов
/ 05 апреля 2011

Шаблон, который я использую для этого, состоит в том, чтобы обернуть каждый тип в модуле и выставить свойства create и prototype, например:

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;
})();

Тогда я могу создавать производные типы следующим образом:

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; 

})();

с этим шаблоном, каждый тип имеет свою собственную функцию create().

0 голосов
/ 08 февраля 2016

Что ж, уже много лет, но для всех, кто оступился на этом.Вы можете использовать Object.assign в FF и Chrome.

В этом примере, когда куб создается с помощью create.Сначала Object.create (this) создает объект со свойством z, затем с Object.assign (obj, Square.create (x, y)) он вызывает метод Square.create, возвращает и добавляет его в Cube, хранящийся в 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);
0 голосов
/ 20 июня 2010

Полезную информацию о наследовании JavaScript можно найти в Центре разработки Mozilla.

0 голосов
/ 20 июня 2010

Вы можете определить Object.create самостоятельно, но если он не является нативным, вам придется иметь дело с перечислением его в каждом цикле for, который вы используете для объектов.

Пока что только новые веб-комплекты - Safari5 и Chrome изначально поддерживают его.

0 голосов
/ 20 июня 2010

Оригинальная документация для Object.create Дугласа находится здесь http://javascript.crockford.com/prototypal.html.Убедитесь, что вы включили определение метода

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