当前位置:首页 > JavaScript

原生js如何实现继承

2026-01-31 00:54:51JavaScript

原型链继承

通过将子类的原型指向父类的实例实现继承。子类实例通过原型链访问父类的属性和方法。

function Parent() {
  this.name = 'parent';
}
Parent.prototype.sayName = function() {
  console.log(this.name);
};

function Child() {}
Child.prototype = new Parent(); // 原型链继承

const child = new Child();
child.sayName(); // 输出"parent"

构造函数继承

在子类构造函数中调用父类构造函数,使用call或apply方法改变this指向。

function Parent(name) {
  this.name = name;
}

function Child(name, age) {
  Parent.call(this, name); // 构造函数继承
  this.age = age;
}

const child = new Child('child', 10);
console.log(child.name); // 输出"child"

组合继承

结合原型链继承和构造函数继承,既继承原型方法又继承实例属性。

function Parent(name) {
  this.name = name;
}
Parent.prototype.sayName = function() {
  console.log(this.name);
};

function Child(name, age) {
  Parent.call(this, name); // 继承属性
  this.age = age;
}
Child.prototype = new Parent(); // 继承方法

const child = new Child('child', 10);
child.sayName(); // 输出"child"

原型式继承

基于已有对象创建新对象,使用Object.create()方法实现。

const parent = {
  name: 'parent',
  sayName: function() {
    console.log(this.name);
  }
};

const child = Object.create(parent);
child.name = 'child';
child.sayName(); // 输出"child"

寄生式继承

在原型式继承基础上增强对象,添加额外方法。

function createAnother(original) {
  const clone = Object.create(original);
  clone.sayHi = function() {
    console.log('hi');
  };
  return clone;
}

const parent = {
  name: 'parent'
};
const child = createAnother(parent);
child.sayHi(); // 输出"hi"

寄生组合式继承

最理想的继承方式,通过借用构造函数继承属性,通过混合式原型链继承方法。

function inheritPrototype(child, parent) {
  const prototype = Object.create(parent.prototype);
  prototype.constructor = child;
  child.prototype = prototype;
}

function Parent(name) {
  this.name = name;
}
Parent.prototype.sayName = function() {
  console.log(this.name);
};

function Child(name, age) {
  Parent.call(this, name);
  this.age = age;
}
inheritPrototype(Child, Parent); // 寄生组合继承

const child = new Child('child', 10);
child.sayName(); // 输出"child"

原生js如何实现继承

标签: 如何实现js
分享给朋友:

相关文章

vue如何实现记住我

vue如何实现记住我

实现“记住我”功能的步骤 在Vue中实现“记住我”功能通常涉及前端保存用户登录状态(如token)到本地存储,并在下次访问时自动恢复登录状态。以下是具体实现方法: 使用localStorage或…

权限管理vue如何实现

权限管理vue如何实现

基于路由的权限控制 在Vue中可以通过路由守卫实现页面级权限控制。定义路由时添加meta字段标记权限角色: const routes = [ { path: '/admin',…

js实现验证

js实现验证

验证表单输入 使用JavaScript验证表单输入是常见的需求。可以通过监听表单提交事件,检查输入字段是否符合要求。 document.getElementById('myForm').addEv…

h5响应式布局如何实现

h5响应式布局如何实现

使用媒体查询(Media Queries) 通过CSS媒体查询针对不同屏幕尺寸设置不同的样式规则。例如: @media screen and (max-width: 768px) { .co…

js实现类

js实现类

JavaScript 实现类的几种方式 JavaScript 是一种基于原型的语言,但在 ES6 之后引入了 class 语法糖,使得实现类更加直观。以下是几种常见的实现方式: 使用构造函数 传统的…

js实现拷贝

js实现拷贝

实现文本拷贝 使用 document.execCommand 方法(已废弃但兼容性较好): function copyText(text) { const textarea = documen…