原型

2020-09-09  本文已影响0人  酒暖花深Q

class 和 继承

子类通过extendssuper 继承父类中的属性和方法
StudentTearcher可以继承people中的nameeat()方法

<script>
        //父类 
        class People {
            constructor(name) {
                this.name = name
            }
            eat() {
                // console.log(this.name + 'eat something')
                console.log(` ${this.name} eat something`)
            }
        }
        // 子类
        class Student extends People{
            constructor(name, number){
                super(name);
                this.number = number
            }
            sayHi(){
                console.log(`姓名 ${this.name} , 学号 ${this.number}`)
            }
        }
        //子类
        class Teacher extends People{
            constructor(name,major){
                super(name);
                this.major = major;
            }
            teach (){
                console.log(`姓名 ${this.name} 教 ${this.major}`) 
            }
        }

        const xialuo = new Student('夏洛','100');
        console.log(xialuo.name)
        console.log(xialuo.number)
        xialuo.sayHi()
        xialuo.eat()
        const laowang = new Teacher('王老师','语文');
        console.log(laowang.name)
        console.log(laowang.major)
        laowang.teach()
        laowang.eat();

        console.log('xialuo.__proto__ 隐式原型 --->'+ JSON.stringify( xialuo.__proto__));
        console.log('Student.prototype 显式原型 --->'+ JSON.stringify(Student.prototype));
Student.prototype === xialuo.__proto__  // true
    </script>

为了好理解可以画图

1.png
xlaluo__proto__Studentprototype指向同一个sayHi();

原型关系

1.每个class都有一个显式的prototyp

2.每个实例都有一个隐式 __proto__

3.实例的 __proto__ 指向对应的classprototyp

执行规则

  1. 获取实例属性xialuo.name或执行方法sayHi()

  2. 先在自身属性和方法中寻找

3.找不到则自动到隐式原型中寻找。如 xialuo中的namenumber是在自身中寻找。sayHi()是在 Student中寻找

上一篇 下一篇

猜你喜欢

热点阅读