技术文摘
如何实现js继承
2025-01-09 12:16:38 小编
如何实现js继承
在JavaScript中,继承是一种强大的特性,它允许对象继承其他对象的属性和方法,有助于代码的复用和结构优化。以下将介绍几种常见的实现JavaScript继承的方式。
原型链继承
这是JavaScript中最基本的继承方式。每个对象都有一个内部属性 [[Prototype]],它指向该对象的原型对象。当访问一个对象的属性或方法时,JavaScript首先会在对象本身查找,如果找不到,就会沿着原型链向上查找。
function Parent() {
this.parentProperty = 'I am a parent property';
this.parentMethod = function() {
console.log('This is a parent method');
};
}
function Child() {}
Child.prototype = new Parent();
let child = new Child();
child.parentMethod();
构造函数继承
通过在子类构造函数中调用父类构造函数,使用 this 关键字将父类的属性和方法复制到子类实例中。
function Parent(name) {
this.name = name;
this.sayName = function() {
console.log('My name is'+ this.name);
};
}
function Child(name, age) {
Parent.call(this, name);
this.age = age;
}
let child = new Child('Tom', 10);
child.sayName();
组合继承
结合了原型链继承和构造函数继承的优点。通过原型链实现方法的继承,通过构造函数实现属性的继承。
function Parent(name) {
this.name = name;
this.sayName = function() {
console.log('My name is'+ this.name);
};
}
Parent.prototype.sayHello = function() {
console.log('Hello from parent');
};
function Child(name, age) {
Parent.call(this, name);
this.age = age;
}
Child.prototype = new Parent();
Child.prototype.constructor = Child;
let child = new Child('Jerry', 12);
child.sayName();
child.sayHello();
寄生组合继承
对组合继承的优化,避免了在创建子类原型时不必要的父类实例创建。
function Parent(name) {
this.name = name;
this.sayName = function() {
console.log('My name is'+ this.name);
};
}
function Child(name, age) {
Parent.call(this, name);
this.age = age;
}
function inheritPrototype(subType, superType) {
let prototype = Object.create(superType.prototype);
prototype.constructor = subType;
subType.prototype = prototype;
}
inheritPrototype(Child, Parent);
let child = new Child('Bob', 15);
child.sayName();
掌握这些继承方式,能让开发者在不同的应用场景中,灵活运用以实现高效、可维护的代码结构,提升JavaScript编程的效率与质量。
- uniapp实现电子商务与在线购物的方法
- HTML与CSS打造瀑布流图库布局的方法
- 深入解析 CSS 定位属性:position 与 top/left/right/bottom
- CSS透明度属性优化妙招:opacity与rgba
- Layui框架开发响应式新闻资讯网站的方法
- Layui框架下开发支持即时查询与预订酒店的旅游服务平台方法
- HTML、CSS 与 jQuery 打造响应式图片滑块的方法
- CSS实现图片展示特效的技巧与方法
- Layui框架开发支持在线预览Word文档应用的方法
- HTML、CSS 与 jQuery 创建响应式网站的方法
- Uniapp 中运用多语言切换技术达成多语言支持的方法
- 纯 CSS 实现图片模糊放大效果的方法与技巧
- 用 HTML、CSS 与 jQuery 打造超炫 3D 翻转卡片
- CSS文本溢出属性text-overflow和ellipsis详解
- CSS空白处理属性详解:whitespace与word-break