简体   繁体   English

使用Object.create()进行JavaScript继承?

[英]JavaScript inheritance with Object.create()?

How do I inherit with the Object.create()? 我如何继承Object.create()? I tried these, but none are working: 我试过这些,但都没有工作:

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

and

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

and

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

Nothing worked. 没有任何效果。 How am I supposed to use this new Object.create()-function? 我该如何使用这个新的Object.create()函数?

There are several ways of doing inheritance in JavaScript 在JavaScript中有几种继承方式

Construction Inheritance. 施工继承。 Used if you don't need to call supertype constructor: 如果您不需要调用超类型构造函数,请使用:

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 Stealing. 构造函数窃取。 Used if need to call supertype constructor: 如果需要调用超类型构造函数则使用:

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

Object.create() is used to inherit objects, not constructors like you're trying to do. Object.create()用于继承对象,而不是像你想要的那样构造。 It pretty much creates a new object with the old object set as its prototypal parent. 它几乎创建了一个新对象,旧对象设置为原型父对象。

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'

And just to make sure b is not just a clone of a, 并且只是为了确保b不仅仅是a的克隆,

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

The pattern I use for this is to wrap each type in a module, and expose create and prototype properties, like so: 我用于此的模式是将每个类型包装在一个模块中,并公开createprototype属性,如下所示:

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

Then I can build derived types like so: 然后我可以像这样构建派生类型:

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; 

})();

with this pattern, each type has its own create() function. 使用此模式,每种类型都有自己的create()函数。

The original documentation for Douglas' Object.create is here http://javascript.crockford.com/prototypal.html . Douglas'Object.create的原始文档在http://javascript.crockford.com/prototypal.html Make sure you have included the definition of the the method 确保已包含该方法的定义

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

You can define Object.create yourself, but if it is not native you will have to deal with it being enumerated in every for in loop you use for objects. 您可以自己定义Object.create,但如果它不是本机的,则必须处理它在用于对象的每个for循环中的枚举。

So far only new webkits- Safari5 and Chrome natively support it. 到目前为止,只有新的webkits-Safari5和Chrome本身支持它。

您可以在Mozilla Development Center上找到有关JavaScript继承的有用信息。

Well it's years late, but for anyone else stumbling upon this. 好吧,它已经晚了几年,但对于其他任何绊脚石的人来说。 You can use Object.assign in FF and Chrome. 您可以在FF和Chrome中使用Object.assign。

In this example when the Cube is being made with create. 在此示例中,使用create制作多维数据集。 First Object.create(this) creates the object with the z property, then with Object.assign(obj, Square.create(x,y)) it will call the Square.create and return and append that into Cube being stored in obj. 第一个Object.create(this)使用z属性创建对象,然后使用Object.assign(obj,Square.create(x,y))它将调用Square.create并返回并将其追加到存储在obj中的Cube中。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM