什么是原型和原型链?原型链继承?

每一个JS函数中都有一个prototype(原型)属性,指向这个函数的原型对象,通过这个函数产生的实例对象都有一个__proto__(隐式原型)属性,这个属性也是指向同一个原型对象,所有的实例对象的属性都会继承这个原型对象的属性,原型对象上也有一个__proto__属性,指向的objec原型对象,所有的对象属性都会继承objec原型对象属性。而object原型对象的__proto__指向的是null。当我们访问对象的某个属性时,就会从实例对象,原型对象,object原型对象上层层寻找,由此形成原型链。而原型就是原型对象上的属性。

 

应用

需要给每个对象都添加一个方法时,显然不可能new出一个对象就添加一个方法,而是在原型对象上添加方法。

在观察者模式、发布订阅模式中,也是通过在原型对象上添加方法和属性实现。

 

手写原型链继承

所谓继承,就是一个对象使用另外一个对象的方法和属性

  • 普通继承方式

这种情况下,父类型的对象原型上不能有任何属性和方法,因为父类型的prototype指向已经不是对象原型了

 //设定一个Parents构造函数
    function Parents(){
        this.job = 'makeMoney'
    }

    //设定一个Child构造函数
    function Child(){
        this.study = 'college'
    }

    //让Parents的原型指向Child的实例对象
    Parents.prototype = new Child()

    const Chen = new Parents
    console.log(Chen.study,Chen.job);

 

 

 

  • 对象原型指向实例对象的继承
 //设定一个Parents构造函数
    function Parents(){
        this.job = 'makeMoney'
        this.Sub = function (){
            console.log('Parents的方法');
        }
    }

    //把方法写在Parents对象原型上
    Parents.prototype.Sud = function (){
        console.log('Parents对象原型上的方法');
    }

    //设定一个Child构造函数
    function Child(){
        this.study = 'college'
        this.Sup = function (){
            console.log('Child的方法');
        }
    }

    //把方法写在Child对象原型上
    Child.prototype.SuC = function () {
        console.log('Child对象原型上的方法');
    }

    //让Parents的原型指向Child的实例对象
    Parents.prototype.__proto__ = new Child()

    const Chen = new Parents
    console.log(Chen.Sub,Chen.Sud,Chen.SuC,Chen.Sup);

这样的话,所有的方法都可以使用

 

 

  •  另外一种继承方式
//属性继承

function Person (name, age) {
    this.name = name
    this.age = age
}

// 方法定义在构造函数的原型上
Person.prototype.getName = function () { console.log(this.name)}

function Teacher (name, age, subject) {
    Person.call(this, name, age)
    this.subject = subject
}

//方法继承

Teacher.prototype = Object.create(Person.prototype)
Teacher.prototype.constructor = Teacher

这种方式的方法继承不是引用关系,而是拷贝关系。两者互补影响

 

posted @ 2020-10-24 16:56  风中逆羽  阅读(1936)  评论(1编辑  收藏  举报