Наследование JavaScript с Object.create()?

Как наследовать объект 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()?

Ответ 1

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.x = 'goodbye';
delete b.x;
b.say(); //alerts 'goodbye'

Ответ 2

Существует несколько способов выполнения наследования в 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

Ответ 3

Образец, который я использую для этого, - это обернуть каждый тип в модуле и показать свойства 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().

Ответ 4

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

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

Ответ 5

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

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

Ответ 7

Хорошо, что он опаздывает, но для кого-то еще наткнулся на это. Вы можете использовать Object.assign в FF и Chrome.

В этом примере, когда Cube создается с помощью create. First 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);