<script>
/*
* js 原型继承
* @params {Function} supperClass; 父类构造函数
*
* @params {Function}; 返回子类构造函数
*/
Function.prototype.prototypeExtend = function(superClass){
var F = function(){},
self = this;
F.prototype = superClass.prototype;//创建过度类,避免父类构造函数执行,避免子类修改原型对象时影响父类原型对象
self.prototype = new F();//重新复制当前类原型对象为实例化一个空对象,此对象__proto__隐式原型指向父类原型对象(js链式搜索属性),间接继承父类原型对象(主要是继承方法)
if(Object.defineProperty){
Object.defineProperty(self.prototype,'constructor',{
enumerable: false,//不可枚举
configurable: true,
writable: true
});
}
self.prototype.constructor = self;//为当前类原型对象设置构造函数指向
F = null;
return self;
}
function Supper(name,age){
this.name = name;
this.age = age;
}
Supper.prototype.sayName = function(){
console.log(this.name);
}
var supperInstance = new Supper('parent',30);
supperInstance.sayName();
//supperInstance.sayJob();//Uncaught TypeError
var Child = (function(name,age,job){
Supper.call(this,name,age);
this.job = job
}).prototypeExtend(Supper);
Child.prototype.sayJob = function(){
console.log(this.job);
};
var childInstance = new Child('snake',20,'coder');
childInstance.sayName();
childInstance.sayJob();
</script>
个人觉得目前比较好的原型继承解决方案,如有不足,欢迎大神指正