简体   繁体   English

javascript中继承的模式

[英]a pattern for inheritance in javascript

This is a really old subject about which much has been written, but I haven't found exactly this spin on it so please bear with me. 这是一个非常古老的主题,关于它已经写了很多,但我还没有找到它的旋转,所以请耐心等待。

After having spent a bit of time trying to get my head around the new and f.prototype constructor constructs in JavaScript, and reading about how it's a prototypal language, not to mention Crockford's illuminating comments on the subject, I have reached the conclusion that the following is a much more natural way to simulate traditional class-based inheritance in JavaScript, should one want to: 在花了一些时间试图了解JavaScript中的newf.prototype构造函数构造,并阅读它是如何成为原型语言之后,更不用说Crockford对该主题的启发性评论了,我得出的结论是以下是在JavaScript中模拟传统的基于类的继承的更自然的方法,如果想要:

// emphasise that there's no superclass instead of writing A = {}
var A = Create.object(null);

// define the 'instance initializer', which half of what a constructor is
A.init = function(x, y) {
    this.x = x;
    this.y = y;
    return this;
}

// a method
A.sum = function() {
    return this.x + this.y;
}

// instantiate A
var a = Object.create(A).init(3);

// a subclass
var B = Object.create(A);

B.init = function(x, y, w) {
    A.init.call(this, x, y);
    this.w = w;
    return this;
}

B.weightedSum = function() {
    return (1.0 - this.w) * this.x + this.w * this.y;
}

// instantiate B
var b = Object.create(B).init(1, 2, 0.3);

// equivalent of `instanceof`
var bInstanceOfA = A.isPrototypeOf(b);

What I like about this is that it exposes what's really going as there is clear separation between object creation (which applies to both instantiation and subclassing) and initialization (which only applies to instantiation). 我喜欢这个,它暴露了真正发生的事情,因为对象创建(适用于实例化和子类化)和初始化(仅适用于实例化)之间存在明显的分离。 Also there is symmetry between creating a base class and a subclass. 在创建基类和子类之间也存在对称性。 The code doesn't require externally defined functions or libraries, but isn't particularly verbose either. 代码不需要外部定义的函数或库,但也不是特别冗长。

My question, therefore, is the following: could those of you who have more experience with JavaScript tell me if there are problems with the approach that I am not considering, or if it is a good pattern? 因此,我的问题如下:对于那些对JavaScript有更多经验的人,能告诉我这个方法是否存在我不考虑的问题,或者它是否是一个好的模式?

You lose a new keyword with this approach. 您使用此方法丢失了new关键字。 So you can't say new A(128, 256) . 所以你不能说new A(128, 256)

But you can use Object.create() for the prototype inheritance and create the regular objects with new keyword in this way: 但是您可以使用Object.create()进行原型继承,并以这种方式使用new关键字创建常规对象:

var Employee = function(name) {
    this.name = name;
    return this;
};

Employee.prototype = {
    doWork: function() {
        console.log('%s is doing some abstract work', this.name);
    }
};

var Driver = function(name) {
    return Employee.call(this, name);
};

Driver.prototype = Object.create(Employee.prototype, {
    doWork: {
        value: function() {
            console.log('%s is driving a car', this.name);
        }
    },
    fixEngine: {
        value: function() {
            console.log('%s is fixing an engine', this.name);
        }
    }
});

var employee = new Employee('Jim');
var driver = new Driver('Bill');

employee.doWork(); // Jim is doing some abstract work 
driver.doWork(); // Bill is driving a car
driver.fixEngine(); // Bill is fixing an engine 

http://jsfiddle.net/f0t0n/HHqEQ/ http://jsfiddle.net/f0t0n/HHqEQ/

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

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