原型 与 原型链

81 阅读1分钟

1.原型

由构造函数创造出来的实例,叫做函数对象,每一个函数对象都有一个原型,我们称之为隐式原型(proto),构造函数这个类也有一个原型,是显示原型(prototype);隐式原型跟显示原型指向的是同一个对象,这就是原型;

//Student构造函数(类)
class Student{
    constructor(name,score){
        this.name = name;
        this.score = score;
    }
    introduce(){
        console.log(`我叫${this.name},考了${this.score}分`)
    }
}

//student由构造函数创造出来的实例
const student = new Student('张三',99);

student.__proto__ === Student.prototype ; //true

2.原型链

当我们访问一个对象的属性或者方法的话,首先会从他自身去找,如果找不到的话,会通过隐式原型上去找,如果原型还找不到的话,会继续往原型的原型上去找,终点是Object.prototype(null)。整个寻找的过程,我们称之为原型链;

class Person {
   constructor(name){
        this.name = name;
    }
    drink(){
        console.log('人类要喝水')
    }
}

//extends,super关键字实现 继承
class Teacher extends Person{
  constructor(name,subject){
        super(name);
        this.subject = subject;
    }
    teach(){
        console.log(`我是${this.name},教${this.subject}科目`)
    }
}

//teacher由构造函数创造出来的实例
const teacher = new Teacher('张三','语文');

teacher.drink();// 人类要喝水(drink是teacher的原型Teacher的原型Person的方法,展示了原型链)

我们可以通过hasOwnProperty方法去判断是否是对象本身的属性或方法;

    Teacher.hasOwnProperty(teach); //true
    Teacher.hasOwnProperty(drink); //false