基本上我喜欢具有instanceof Something === true
的功能。
类似于MySpecialKindOfFunction
,例如:
if (theFunction instanceof MySpecialKindOfFunction)
我尝试过设置 proto 和函数的构造函数而没有工作。
答案 0 :(得分:0)
也许我不明白你的问题,但这是你想要达到的目标吗?
// Static class method.
Interface.ensureImplements = function(object) {
if(arguments.length < 2) {
throw new Error("Function Interface.ensureImplements called with " +
arguments.length + " arguments, but expected at least 2.");
}
for(var i = 1, len = arguments.length; i < len; i++) {
var interface = arguments[i];
if(interface.constructor !== Interface) {
throw new Error("Function Interface.ensureImplements expects arguments"
+ " two and above to be instances of Interface.");
}
for(var j = 0, methodsLen = interface.methods.length; j < methodsLen; j++) {
var method = interface.methods[j];
if(!object[method] || typeof object[method] !== 'function') {
throw new Error("Function Interface.ensureImplements: object "
+ "does not implement the " + interface.name
+ " interface. Method " + method + " was not found.");
}
}
}
};
我使用此代码来测试函数是否是一种接口。关键代码是:
if(interface.constructor !== Interface) {
要扩展课程,您可以这样做:
function Item () {
};
function Picture () {
Item.call(this); // Call to superClass constructor with subclass instance
};
Picture.prototype = new Item();
Picture.prototype.constructor = Picture;
var picture = new Picture();
if(picture instanceof Item){
alert("True");
} else {
alert(false);
}