We can use the prototype chain to implement the inheritance of methods from a super class.
- The method most people use:
Note: this will always call the supper's constructor and it is just a waste in some way.function inherit(sub, supper){ var subProto = sub.prototype = new supper(); subProto.constructor = sub; }
- The method not really inheritance:
Note: the result of new Sub() instanceof Supper is false.function inherit(sub, supper){ var subProto = sub.prototype, supProto = supper.prototype; for(var i in supProto){ if(!subProtp[i]) subProto[i] = supProto[i]; } } - The method derives from method 1:
function inherit(sub, supper){ var subProto = sub.prototype; subProto = Object.create(supper.prototype); subProto.constructor = sub; } function inherit(sub, supper){ var subProto = sub.prototype; var F = function(){}; F.prototype = supper.prototype; subProto = new F(); subProto.constructor = sub; }
- The method
simplest but IE doesn't support:
function inherit(sub, supper){ sub.prototype.__proto__ = supper.prototype; }
本文介绍了JavaScript中实现继承的多种方法,包括使用原型链、直接复制属性以及利用构造函数等方式,并对比了不同方法的特点与局限性。
1269

被折叠的 条评论
为什么被折叠?



