1.原型链
JavaScript规定,所有对象都有自己的原型对象(prototype)。一方面,任何一个对象,都可以充当其他对象的原型
<script>
/* 为什么一个实例化的对象能够使用它原型上的方法 */
function Person(name,age){
this.name = name;
this.age = age;
}
Person.prototype.sayName = function(){
console.log(this.name)
}
/*
1.每个对象都有一个隐藏属性__proto__,它指向它的原型对象
2.这个对象会享有原型上的属性或者方法
*/
var wang = new Person("wangyuhuan",18)
console.log(wang)
// wang.sayName = function(){
// console.log("wang")
// }
// wang.sayName()
console.log(wang.__proto__) //里面有sayname()
console.log(wang.__proto__==Person.prototype) //true
</script>
2.继承
<script>
// function Person(name,age){
// this.name = name;
// this.age = age;
// }
// Person.prototype.sayName = function(){
// this.name;
// }
class Person{
constructor(name,age){
this.name= name;
this.age = age
}
sayName(){
console.log(this.name)
}
}
/* 使用extends关键可以实现继承,之后自动拥有父类的属性和方法 */
class Student extends Person{
constructor(name,age,skill){
super(name,age);
this.skill = skill
}
saySkill(){
console.log(this.skill)
}
}
var cheng = new Person("chengchao",18);
/* 父类不能使用子类的方法 */
cheng.saySkill()
var s = new Student("lisi",17,'js')
// s.sayName()
console.log(s.__proto__) //Person
</script>
<script>
/*
1. class实现一个类
2. constructor关键字实现构造函数
3.类中的方法是写在原型上的
4.extends关键字能够实现继承
5.在子类的方法中去调用父类的方法使用this就可以调用
*/
/*
1.es5构造函数--实现了类
2.new关键字实例化了对象
3.原型
4.原型链
*/
class Person{ //Person类
constructor(name,age){
this.name= name;
this.age = age
} //构造函数
sayName(){
console.log(this.name) //构造函数方法
} //写在原型对象上
}
/* 在子类的方法中去调用父类的方法 */
class Student extends Person{
constructor(name,age,skill){
super(name,age);
this.skill = skill
}
saySkill(){
this.sayName()
}
}
var cheng = new Student("lisi",12,'js');
cheng.saySkill()
var p = new Person("zhangsan",18)
console.log(Person.prototype) //有sayName
</script>