I have a class definition method for create class in javascript:
var Class = function() {
var clazz = null,
pros = {};
for (var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
if (typeof arg == "function") arg = arg.prototype;
else {
arg.init && (clazz = arg.init, delete arg.init)
}
for (var p in arg) pros[p] = arg[p];
}
clazz.prototype = pros;
return clazz;
};
var Person = Class({
init: function(name) {
this.name = name;
},
say:function(){
console.info(this.name);
}
});
var Man = Class(Person, {
init: function(name) {
Person.apply(this, arguments);
this.gender = 'man'
}
});
var m = new Man('kk');
console.info(m instanceof Man);
console.info(m instanceof Person);
However, it does not support the instanceof operator.
Any idea to fix it?
You should keep track of the prototype chain to make
instanceofwork. What you’re currently doing is merely copying properties into one object, and use that as prototype of the returned function. As a result, the information thatParentis a parent ofManis lost.You’d need to set the prototype instead of copying.
Since you need to modify an existing object to set the underlying prototype of, the deprecated__proto__property is required.Object.createcannot be used here, because that returns a new object.Edit: It is possible without
__proto__, but you’d need thefunction Ftrick: http://jsfiddle.net/p9pvQ/.mwill then have the prototype chain as follows: