大厂必面,js继承封装
- 话不多说,直接上代码
Function.prototype.extends = function (superClass) {
//声明一个变量,将原有原型对象存储起来
var o = this.prototype;
function F() {}
F.prototype = superClass.prototype;
this.prototype=new F();
//获取当前类所有属性名
var names=Object.getOwnPropertyNames(o);
//遍历所有属性名,获取属性名的属性描述
for(var i=0;i<names.length;i++){
var desc=Object.getOwnPropertyDescriptor(o,names[i]);
//将当前原型与被继承的原型对象结合
Object.defineProperty(this.prototype,names[i],desc);
}
//将继承的类,定义为当前原型链上一个超类
this.prototype.superClass=superClass;
//判断当前原型对象原型是否为该原型对象,不是则赋值为对应的原型对象
if(this.prototype.constructor!==this){
Object.defineProperty(this.prototype,"constructor",{
value:this
})
}
//判断当前继承对象原型是否为继承的原型对象,不是则赋值为对应的原型对象
if(superClass.prototype.constructor!==superClass){
Object.defineProperty(superClass.prototype,"constructor",{
value:superClass
})
}
};
- 简单示例
function CheckBox(){
}
CheckBox.prototype={
a:1,
b:function(){
}
}
function Radio(){
this.superClass.apply(this,arguments);
}
Radio.prototype={
c:10,
d:function(){
}
}
Radio.extends(CheckBox);
var r=new Radio();
console.log(r);
版权声明:本文为Boring_com原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。