JS 常用继承
原文出处:爱睡觉的小猫咪
1.原型链继承
function SuperType() {
this.property=true;
}
SuperType.prototype.getSuperValue=function () {
return this.property;
};
function SubType() {
this.subproperty=false;
};
SubType.prototype=new SuperType();
SubType.prototype.getSubValue=function () {
return this.subproperty;
}
var instance=new SubType();
2.构造函数继承
function SuperType(name) {
this.name=name;
}
function SubType() {
SuperType.call(this,'Nicholas');
this.age=29;
}
var instance=new SubType();
console.log(instance.name+' '+instance.age);//Nicholas 29
3.组合继承
function SuperType(name) {
this.name=name;
this.colors=['red','blue','green']
}
SuperType.prototype.sayName=function () {
console.log(this.name);
}
function SubType(name,age) {
SuperType.call(this,name);
this.age=age;
}
SubType.prototype=new SuperType();
SubType.prototype.sayAge=function () {
console.log(this.age);
}
var instance1=new SubType('Nicholas',29);
instance1.colors.push('black');
console.log(instance1.colors);
instance1.sayName();
instance1.sayAge();
var instance2=new SubType('Greg',27);
console.log(instance2.colors);
instance2.sayName();
instance2.sayAge();
4.组合寄生继承
//将组合继承中的实例化继承:
//SubType.prototype=new SuperType();
//改为浅拷贝继承:
function Object.create(o){
function F() {};
F.prototype=o;
return new F();
}
function inheritPrototype(subType,superType){
var prototype=Object.create(superType.prototype);//创建对象
prototype.constructor=subType;
subType.prototype=prototype;
}
inheritPrototype(SubType,SuperType);
感谢您的阅读,如果您对我的文章感兴趣,可以关注我的博客,我是叙帝利,下篇文章再见!
高颜值的渐变编辑器组件,支持所有 CSS 渐变语法 https://github.com/acrodata/gradient-picker
一款小而美的颜色选择器组件 https://github.com/acrodata/color-picker
低代码平台必备轻量级 GUI 库 https://github.com/acrodata/gui
适用于 Angular 的 CodeMirror 6 组件 https://github.com/acrodata/code-editor
适用于 Angular 的水印组件(防删除,盲水印) https://github.com/acrodata/watermark
支持拖拽和缩放的弹窗组件 https://github.com/acrodata/rnd-dialog
开发低代码平台的必备拖拽库 https://github.com/ng-dnd/ng-dnd
基于 Angular Material 的中后台管理框架 https://github.com/ng-matero/ng-matero
Angular Material Extensions 扩展组件库 https://github.com/ng-matero/extensions
Unslider 轮播图插件纯 JS 实现 https://github.com/nzbin/unsliderjs
仿 Windows 照片查看器插件 https://github.com/nzbin/photoviewer
仿 Windows 照片查看器插件 jQuery 版 https://github.com/nzbin/magnify
完美替代 jQuery 的模块化 DOM 库 https://github.com/nzbin/domq
简化类名的轻量级 CSS 框架 https://github.com/nzbin/snack
与任意 UI 框架搭配使用的通用辅助类 https://github.com/nzbin/snack-helper
单元素纯 CSS 加载动画 https://github.com/nzbin/three-dots
有趣的 jQuery 卡片抽奖插件 https://github.com/nzbin/CardShow
悬疑科幻电影推荐 https://github.com/nzbin/movie-gallery
锻炼记忆力的小程序 https://github.com/nzbin/memory-stake

浙公网安备 33010602011771号