我正在通过专业JavaScript为网络开发人员工作,并且有一个关于对象创建和继承的问题。在本书中,讨论了动态原型模式作为一种很好的方法来完成组合构造器/原型模式,同时将构造函数和原型封装到对象定义中。如下所示:
function Person(name, age, job) {
this.name = name;
this.age = age;
this.job = job;
if (typeof this.sayName != "function") {
Person.prototype.sayName = function () {
return this.name;
};
}
}在书中讨论的所有对象创建模式中,我觉得这个看起来最好。然后在讨论继承时,书中说寄生组合继承被认为是最优的继承范式。详情如下:
function inheritPrototype(subType, superType) {
var prototype = Object.create(superType.prototype);
prototype.constructor = subType;
subType.prototype = prototype;
}
function SuperType(name) {
this.name = name;
this.colors = ['red', 'blue', 'green'];
}
SuperType.prototype.sayName = function() {
return this.name;
};
function SubType(name, age) {
SuperType.call(this, name);
this.age = age;
}
inheritPrototype(SubType, SuperType);
SubType.prototype.sayAge = function() {
return this.age;
}如您所见,这段代码使用Constructor/Prototype模式创建对象,其中原型在原始对象创建之外声明。我的问题是,将动态原型模式与寄生组合继承结合起来有什么问题吗?
function inheritPrototype(subType, superType){
var prototype = Object.create(superType.prototype);
prototype.constructor = subType;
subType.prototype = prototype;
}
function SuperType(name) {
this.name = name;
this.colors = ['red', 'blue', 'green'];
if (typeof this.sayName != "function") {
SuperType.prototype.sayName = function() {
return this.name;
};
}
}
function SubType(name, age) {
SuperType.call(this, name);
this.age = age;
if (typeof this.sayAge != "function") {
SubType.prototype.sayAge = function() {
return this.age;
};
}
}
inheritPrototype(SubType, SuperType);我已经在一个jsfiddle 这里中测试过这一点,它看起来很好,我只是想确保我没有遗漏什么东西会在以后使用这种模式/继承时造成问题。
而且,正如我所知道的,这本书更老了一点,是否有新的对象创建和继承标准?
发布于 2016-10-23 12:49:27
两种方法似乎都失败了。
即使构造函数尚未被调用,给定的对象原型属性也应该是可用的。另一方面,这似乎打破了单一责任原则,因为构造器负责定义原型,而它只应该初始化正在构造的对象的。
只有一个问题:如何在构建基本对象之前继承给定对象的原型?
var B = Object.create(A.prototype);等等!A.prototype不会包含预期的属性,除非一些代码之前调用了new A()!
// Ugly as hell!
new A();
var B = Object.create(A.prototype);总之,不要尝试快捷JavaScript:最好学习它,不要试图用无用/无意义的函数包装继承。
实际上,ECMA-Script6及以上的标准已经定义了语法糖,以使JavaScript原型链看起来像古典继承:
class B extends A
{
}...which完全等同于:
function B() {}
B.prototype = Object.create(A.prototype);https://stackoverflow.com/questions/40190465
复制相似问题