JavaScript基于原型链的继承实现示例

作者:纸飞机

时间:2026-10-29

浏览:111

本文通过具体代码实例,展示了JavaScript中基于原型的继承机制。内容涵盖如何定义父类Person,利用Student构造函数调用父级构造器,并通过实例化父类原型实现继承。代码演示了方法重写、原型链检查及实例方法的调用过程,旨在帮助开发者理解JavaScript面向对象编程中的继承模式。

文章目录

JavaScript原型继承代码详解

本文通过具体代码示例,详细解析了JavaScript中继承机制的实际应用。该案例旨在为读者提供直观的参考,便于理解相关技术细节。


// define the Person Class
function Person() {}
Person.prototype.walk = function(){
 alert ('I am walking!');
};
Person.prototype.sayHello = function(){
 alert ('hello');
};
// define the Student class
function Student() {
 // Call the parent constructor
 Person.call(this);
}
// inherit Person
Student.prototype = new Person();
// correct the constructor pointer because it points to Person
Student.prototype.constructor = Student;
// replace the sayHello method
Student.prototype.sayHello = function(){
 alert('hi, I am a student');
}
// add sayGoodBye method
Student.prototype.sayGoodBye = function(){
 alert('goodBye');
}
var student = new Student();
student.sayHello();
student.walk();
student.sayGoodBye();
// check inheritance
alert(student instanceof Person); // true 
alert(student instanceof Student); // true

期望上述内容能对各位在进行JavaScript程序设计时提供有益的参考与帮助。

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章