<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
class Xsen{
name='ABC'
age=18
xbx(){
console.log(`hi~我是:${this.name},今年${this.age}岁`)
}
}
class XXA{
name='BCD'
age=19
xby=()=>{
console.log(`hi~我是:${this.name},今年${this.age}岁`)
}
//这里把xby方法存到对象自身里,则后面的Bma!=Bma2
}
const Ama=new Xsen()
const Ama2=new Xsen()
const Ama3=new Xsen()
const Bma=new XXA()
const Bma2=new XXA()
console.log(Ama===Ama2) // 同一个对象? F
console.log(Ama.__proto__===Ama2.__proto__) //同一个原型对象? T
console.log(Bma.xby===Bma2.xby) //F
console.log(`-------1-------`)
/* 同类型对象的原型对象都是同一个,也就说明原型链相同
Ama,Ama2数据一样(原型对象相同),但不是同一个对象
原型就相当于一个公共区,可被所有该类实例访问(共享方法)
公共厕所(方法),人类,不分男女(属于该类实例)
*/
console.log(Ama.xbx="hi")//尝试更改方法是否对Ama2影响?
console.log(Ama2.xbx()) //结果
console.log(`-------2-------`)
//继承通过原型实现 Extends
//继承时,子类原型就是父类的实例
class AAA{
number=1
} //父类
class BBB extends AAA{
age=10
} //子类
const er=new BBB()
const fu=new AAA()
console.log(er.number)//子用父 结果为1
console.log(er.__proto__)//原型是AAA
console.log(fu.age)//父用子 undefined
console.log(er.__proto__.__proto__.__proto__.__proto__)//null
// 原型链:
// AAA-->obj-->obj原型-->null
// BBB-->AAA实例-->obj-->obj原型-->null
// 可以说BBB的原型是AAA 随着层级增多 原型链会增加
console.log(`-------3-------`)
//关于修改原型
class Xiugai{
name='cde'
age=15
xbz(){
console.log(`hei!`)
}
}
const Cma= new Xiugai()
const Cma2= new Xiugai()
Cma.__proto__.run=()=>{
console.log("No!")
} //X
Cma.run()
Cma2.run()
//
/*通过类的实例修改原型,原型中添加方法,需要创建实例,且改后此处Cma2也会受到影响
也就是通过一对象影响所有同类对象
注:直接给对象赋新原型更不行 如 Cma.__proto__=new Cma3()
*/
//通过类的prototype属性,访问实例的原型
//不用创建实例
Xiugai.prototype.qifei=()=>{
console.log("起飞")
}
//const Cma3= new Xiugai()
Cma.qifei()
</script>
</body>
</html>
记得复习!