关于利用原型的特性实现继承
来源:1-1 课程简介
若雨灬
2021-08-26 17:24:01
function Student(name, age, sex, school, num) {
this.name = name;
this.age = age;
this.sex = sex;
this.school = school;
this.num = num;
}
// 实现继承的关键语句
Student.prototype = new People();
//Student.prototype = People.prototype;
Student.prototype.study = function () {
console.log(this.name + '正在学习');
}
Student.prototype.exam = function () {
console.log(this.name + '正在考试……');
}
var hanmeimei = new Student('韩梅梅', '14', '女', '上海中学', '001');

1回答
同学你好,对于你的问题解答如下:
1、因为Student实例化对象,可以通过__proto__访问到Student.prorotype上的属性和方法,将People的实例对象赋值给Student.prototype,此时的Student.prototype指向People实例对象,那么即可访问People实例对象上的属性和方法,又可以通过People实例对象的__proto__访问到添加在People原型对象prototype上的属性和方法。
实例:

由输出结果可知,可以继承Peolpe实例对象和原型对象上的属性,返回对应的结果,如下:

2、Student.prototype = People.prototype; 这种写法是可以的,也能够实现继承。
与上一种写法的区别就是:只能继承People原型对象prototype上的属性和方法,不能继承People实例对象上的属性和方法。
示例:

由输出结果可知,Student实例对象hanmeimei无法继承到People实例对象上的属性和方法,所以访问test1返回结果为undefined,可以正常访问People原型对象上的属性test2。如下:

祝学习愉快~
相似问题