javascript 通过原型链和构造函数实现继承。使用原型链,父对象作为子对象的原型,子对象继承父对象的属性和方法。使用构造函数,子构造函数将父构造函数作为原型,并通过覆盖父类方法实现定制化。本例中,person 是父类,employee 是子类,employee 继承了 person 的属性和方法,并添加了自己的 sayjob 方法。
在原生 JavaScript 中实现继承
JavaScript 是一种基于原型链的语言,它不直接支持类和继承,但是可以通过使用原型链和构造函数来模拟继承。
使用原型链实现继承
- 创建父对象:创建一个对象作为父对象,它包含要继承的属性和方法。
const Parent = { name: "Parent", sayName() { console.log(this.name); } };
登录后复制
- 创建子对象:创建子对象,将父对象的原型链设置为其原型。
const Child = Object.create(Parent); Child.name = "Child";
登录后复制
使用构造函数实现继承
- 创建父构造函数:创建一个父构造函数,它包含要继承的属性和方法。
function Parent(name) { this.name = name; } Parent.prototype.sayName = function() { console.log(this.name); };
登录后复制
- 创建子构造函数:创建子构造函数,将父构造函数作为其原型。
function Child(name) { Parent.call(this, name); } Child.prototype = Object.create(Parent.prototype); Child.prototype.constructor = Child;
登录后复制
在子类中覆盖父类方法
要覆盖父类中的方法,可以在子类的原型链中重新定义该方法。
Child.prototype.sayName = function() { console.log("Child: " + this.name); };
登录后复制
示例
以下是一个使用构造函数实现继承的示例:
function Person(name) { this.name = name; } Person.prototype.sayName = function() { console.log(this.name); }; function Employee(name, title) { Person.call(this, name); this.title = title; } Employee.prototype = Object.create(Person.prototype); Employee.prototype.constructor = Employee; Employee.prototype.sayJob = function() { console.log(this.name + " is a " + this.title); }; const john = new Employee("John", "Software Engineer"); john.sayName(); // 输出:"John" john.sayJob(); // 输出:"John is a Software Engineer"
登录后复制
以上就是原生js如何实现继承的详细内容,更多请关注GTHOST其它相关文章!