原型和原型链

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>040-class定义类.html</title>
</head>
<body>
原型就是prototype (该对象所有属性和方法),详见下面证明1
<hr>
每个对象都有prototype。null对象除外
<hr>
继承:子类拥有父类的所有属性和方法(包括静态方法)
<br>给子类添加属性和方法,不影响父类。
<hr>
注:类不存在变量提升
</body>
<script>
class Father{
//定义属性
constructor(name,age){
this.name=name;
}
//定义方法(不用逗号隔开)
showName(){
console.log('I am '+this.name)
}
//定义静态方法
static showTime(){
console.log(Date());
}
}
//子类继承
class Son extends Father{
constructor(name,hobby){
super(name);
this.hobby=hobby;
}
sayHobby(){
console.log('I like '+this.hobby)
}
static sayBaby(){
console.log('baby');
}
}
//实例化
const s1 = new Son('haom2','movie');


//证明1:prototype包含所有属性和方法(动态方法)
//如果可以调用则证明含有
console.log(Father.prototype.name);//undefined证明可以调用属性
Father.prototype.showName();//I am undefined证明可以调用方法

//注意:静态方法只能构造函数
Father.showTime();
Son.showTime();//子类也继承静态方法


//证明2:__proto__指向上一层对象
// 继承的是prototype,所以上一层指向prototype
console.log(s1.__proto__ === Son.prototype);//true
console.log(Son.prototype.__proto__ === Father.prototype);//true
console.log(Father.prototype.__proto__ === Object.prototype);//true
console.log(Object.prototype.__proto__ === null);//true
</script>
</html>

 

posted @ 2020-07-01 13:44  haom  Views(204)  Comments(0Edit  收藏  举报