javascript中的继承模式
这是一个非常古老的主题,已经写了很多,但我还没有找到关于它的确切的旋转,所以请容忍我 在花了一点时间尝试了解JavaScript中的javascript中的继承模式,javascript,inheritance,constructor,instantiation,subclassing,Javascript,Inheritance,Constructor,Instantiation,Subclassing,这是一个非常古老的主题,已经写了很多,但我还没有找到关于它的确切的旋转,所以请容忍我 在花了一点时间尝试了解JavaScript中的new和f.prototype构造函数构造并了解它是一种原型语言之后,更不用说Crockford对该主题的启发性评论了,我得出的结论是,以下是在JavaScript中模拟传统的基于类的继承的更自然的方法,如果您想: // emphasise that there's no superclass instead of writing A = {} var A = Cr
new
和f.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);
我喜欢的是,它揭示了真正发生的事情,因为对象创建(同时适用于实例化和子类化)和初始化(仅适用于实例化)之间存在着明显的分离。创建基类和子类之间也存在对称性。代码不需要外部定义的函数或库,但也不是特别详细
因此,我的问题是:那些对JavaScript有更多经验的人能否告诉我,这种方法是否存在我没有考虑的问题,或者它是否是一种好的模式?使用这种方法会丢失一个
新的关键字。所以你不能说新的A(128256)
但是您可以使用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
仅适用于IE>=9。非常感谢。。。我相信,如果有人愿意的话,添加它应该是非常简单的?我主要在node中编程,所以这不是我主要关心的问题。还有什么问题吗?反正有一个for对象。create()
。但这种方法不能使用new
关键字。这扩展了对象,而不是原型。最大的问题是“为什么”。就连Crockford也说,试图模仿经典继承不是一个好主意,他认为javascript中不需要复杂的继承方案。是的,我同意,但当你来自其他语言时,要想摆脱传统的OOP并不容易。。。这就是为什么我喜欢这种方法。。。没有像《新代码》那样的“幕后魔术”,所以你可以开始习惯新的想法,而不是停留在老井上这是我的全部观点,我不想使用new
关键字,因为它感觉像是一种语言特性,被标记在上面,使JavaScript看起来像是有类的。我的模式提醒您,就JavaScript而言,实例只是初始化的子类(或者子类是未初始化的实例:D)。new
关键字掩盖了这种对称性。