我正在尝试创建一个简单的辅助函数来自动执行 javascript 继承。像这样工作:
var myClass = makeClass({
inherit: SomeSuperClass, //optional, obviously
constructor: function() {} // would like for this to be optional
anotherMethod: function(){} // just gets added to the prototype chain.
// etc
});
我的一切都运行良好,而且非常轻巧,但我遇到了一个错误,它告诉我我并不真正理解我在做什么。从 https://stackoverflow.com/a/22316035/2475951 的精彩答案开始工作我有以下内容:
function makeClass(properties) {
// If the user doesn't supply a constructor, give them a generic function
if ( ! properties.constructor ){
properties.constructor = function(){};
}
if (properties.inherit) {
properties.constructor.prototype = Object.create(properties.inherit.prototype);
properties.constructor.prototype.constructor = properties.constructor;
}
return properties.constructor;
// Plus a simple loop to add the remaining methods given in properties to the prototype chain. Not important here
}
现在开始实现。这按预期工作。
var Food = makeClass({
constructor: function(){}
});
var Bread = makeClass({
inherit: Food,
constructor: function(){}
});
var Sushi = makeClass({
inherit: Food,
constructor: function(){}
});
var bread = new Bread();
var sushi = new Sushi();
console.log(sushi instanceof Bread); // false
console.log(bread instanceof Sushi); // false
console.log(sushi.constructor); // [Function: Sushi]
console.log(bread.constructor); // [Function: Bread]
console.log(sushi instanceof Food); // true
console.log(bread instanceof Food); // true
console.log(sushi instanceof Sushi); // true
console.log(bread instanceof Bread); // true
我的问题是 Bread 或 Sushi 没有提供构造函数。如果 Bread 不提供构造函数,因此使用在 makeClass() 中创建的通用函数,则:
(sushi instanceof Bread) become **true**
如果 Sushi 不提供构造函数,则面包将成为 Sushi 的一个实例。为什么会这样?我可以理解它们的计算结果是真还是假,但为什么删除 Bread 的构造函数会影响寿司实例?我想我的问题是将一个空函数分配给 properties.constructor(如果它是 void),但我不知道该怎么做。
如果我想做的事情是不可能的,或者不是最佳实践,我也想知道。尽管如此,我似乎还缺少一些非常基本的东西。我已经在 SO 和谷歌上搜索了几个小时,但似乎找不到同样的问题。
谢谢!
最佳答案
If Bread doesn't supply a constructor, thus using the generic function created in makeClass()
不完全是。 properties.constructor
,您在您的条件下对其进行测试,将 ( almost ) 始终具有一个值:它继承 .constructor
来自 Object.prototype
.这将使您的 makeClass()
调用返回 Object
函数,而 sushi
确实是一个 instanceof Object
。
所以这是我们需要使用 hasOwnProperty
method 的情况之一。 :
…
// If the user doesn't supply a constructor, give them a generic function
if ( !properties.hasOwnProperty("constructor") ){
properties.constructor = function(){};
}
…
关于javascript - 使用空函数作为继承的构造函数会混淆 javascript 中的 instanceof?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27020711/