HarmonyOS应用实战开发-手写JS中的继承实现以及New、this、instanceof
warning:
这篇文章距离上次修改已过193天,其中的内容可能已经有所变动。
// 定义一个基类,Person
function Person(name) {
this.name = name;
}
Person.prototype.sayHello = function() {
console.log('Hello, my name is ' + this.name);
};
// 定义一个派生类,Student,继承自Person
function Student(name, grade) {
// 调用Person的构造函数来初始化属性
Person.call(this, name);
this.grade = grade;
}
// 实现继承,将Person的原型赋给Student的原型
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;
// 为Student添加新的方法
Student.prototype.sayGrade = function() {
console.log('I am in grade ' + this.grade);
};
// 使用new关键字创建Student实例
var john = new Student('John', 10);
// 使用instanceof检查john的实例关系
console.log(john instanceof Person); // true
console.log(john instanceof Student); // true
// 使用this关键字访问当前对象的属性
john.sayHello(); // Hello, my name is John
john.sayGrade(); // I am in grade 10
这段代码展示了如何在JS中使用构造函数和原型链实现继承,并且演示了如何使用new
关键字创建对象实例,以及如何使用this
和instanceof
来访问属性和检查实例关系。这是学习面向对象编程和JavaScript语言基础的一个很好的例子。
评论已关闭