我正在试验(对我而言)一种新型的继承。我想用一个决定返回哪个继承者对象的参数来调用继承的函数。
这是一个示例来说明我的意思:
function Localizor(type) {
this.language = "English"
this.endonym = "English"
if (window[type]) {
return new window[type]()
}
}
Localizor.prototype.native = function native() {
return "I speak " + this.endonym
}
Localizor.prototype.english = function () {
return "I speak " + this.language
}
function French () {
this.language = "French";
this.endonym = "français"
}
French.prototype = new Localizor()
French.prototype.native = function french() {
return "Je parle " + this.endonym
}
function Thai () {
this.language = "Thai";
this.endonym = "ไทย"
}
Thai.prototype = new Localizor()
Thai.prototype.native = function thai() {
return "พูดภาษา" + this.endonym
}
如果我new Localizor()
在没有参数(或无效参数)的情况下调用,我会得到一个简单的英语对象。如果我用“法语”或“泰语”的参数调用它,我会得到一个对象,其中继承者覆盖了一些继承的方法,因此它说法语或泰语。例如:
var thai = new Localizor("Thai")
var feedback = thai.language + " | " + thai.endonym + " | " + thai.english() + " | " + thai.native()
console.log(feedback)
这给了我输出Thai | ไทย | I speak Thai | พูดภาษาไทย
。
我有三个问题:
1. 这种类型的继承是否已经记录在某个地方(它有名字)吗?
2. 这样工作有什么危险吗?
3. 这个例子检查 的存在window[type]
,这在浏览器中工作时很好。如果这是在 node.js 的模块中,是否有确定模块中是否存在函数的等效方法?
编辑以回应 Zero21xxx
这是我发现的一种检测模块中是否存在构造函数的方法,但对我来说它看起来很危险的乱伦。它有什么风险?有什么更好的方法可用?
function extend(Child, Parent) {
function F() {}
F.prototype = Parent.prototype
Child.prototype = new F()
//Child.prototype.constructor = Child
Child.parent = Parent.prototype
}
function Localizor(type) {
this.language = "English"
this.endonym = "English"
this.French = function français () {
this.language = "French";
this.endonym = "français"
}
extend(this.French, this)
this.French.prototype.native = function french() {
return "Je parle " + this.endonym
}
this.Thai = function ไทย () {
this.language = "Thai";
this.endonym = "ไทย"
}
extend(this.Thai, this)
this.Thai.prototype.native = function thai() {
return "พูดภาษา" + this.endonym
}
if (typeof this[type] === "function") {
return new this[type]()
}
}
Localizor.prototype.native = function native() {
return "I speak " + this.endonym
}
Localizor.prototype.english = function () {
return "I speak " + this.language
}
module.exports = Localizor