关于原型继承
来源:6-1 原型继承
hyperse
2019-05-29 23:51:17
老师课上讲的内容,不知道我做的注释笔记对不对?
以及我感觉关键的一行代码就是student.prototype = new person("lse",19);
就是说student这个对象的原型是person,我可不可以理解成java里面的类,person是类,student是这个类的实例?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>原型继承:用到原型链的概念</title>
</head>
<body>
<script>
// js 继承:
//原型继承: 用到原型链的概念
function person(name,age){
this.name = name;
this.age = age;
}
person.prototype.sayhello = function(){
alert("属性name值:"+this.name);
}
// var per = new person("zhangsan",20);
// per.sayhello();
function student(){};
student.prototype = new person("lse",19); //继承一定是用父类去实例化的。此处体现的是原型继承的概念,要传参。
student.prototype.grade = 3;
student.prototype.test = function(){
alert(this.grade);
}
var s = new student();
alert(s.grade); //3
s.sayhello(); //属性name值:lse
//29行分析:对象s中是没有sayhello()方法的,
//去s.__proto__ 中去找,s等于new student(),那么s.__proto__就等于student.prototype,
//student在prototype里面是实例化成了new person()
//在new person和student找一个中间量p1,p1=new person(),
//但是p1里面也没有sayhello方法,那就在p1.__proto__中找,
//而p1.__proto__就等于person.prototype,就可以找到sayhello方法
//p1可以理解为programmer.prototype == p1 --> p1.__proto__ == person.prototype.say();
; </script>
</body>
</html>
1回答
好帮手慕星星
2019-05-30
你好,可以参考下面的解释:
1、同学的注释没有问题。
2、不能说student这个对象的原型是person,因为在student原型除了继承person的实例,还有添加自己的属性和方法。
3、尽量不要和java做比较,student本身也是一个类,只不过在原型上有继承person的实例。
祝学习愉快!
相似问题