原型链和面向对象

1.创建对象有几种方法

// 对象字面量
var o1 = {name:'o1'}
var o11 = new Object({name:'011'})
// 构造函数
var M = new Function(){this.name=m}
var m =new M()
// 用对象的原型创建
var P={name:'o3'}
var o3 = Object.create(P)

2.原型链

这里写图片描述

3. instanceof 原理

  • 实例对象的proto 和构造函数的protoType 是否是同一个引用
    这里写图片描述

4.类的声明

//类的声明
function Animal (name) {
    this.name = name;
}

//    es6
class Animal2 {
    constructor () {
        this.name = 'a'
    }
}

 //实例化
new Animal('ss');
new Animal2();

5. 类的继承方式

 /*
    * 借助构造函数实现继承
    * 缺点:Parent1原型对象上的属性和方法 不能被继承
    * */
    function Parent1 () {
        this.name = 'parent1'
    }

    function Child1 () {
        Parent1.call(this)// 将父级构造函数this 指向子类构造函数
        this.type = 'child1'
    }

    console.log(new Child1())

    /*
    * 借助原型链继承
    * 缺点:父类属性和方法修改,子类不同实例的属性或方法会一起修改
    * */
    function Parent2 () {
        this.name = 'parent1'
    }

    function Child2 () {
        this.type = 'child1'
    }
    Child2.prototype = new Parent2();

    /*
    * 组合方式
    *  缺点:父级的构造函数执行了两次
    * */
    function Parent3 () {
        this.name = 'parent1'
    }

    function Child3 () {
        Parent3.call(this)
        this.type = 'child1'
    }
    Child3.prototype=new Parent3()

    /*
    * 组合继承的优化1
    *  缺点:子类constructor指向出现错误
    * */

    function Parent4 () {
        this.name = 'parent1'
    }

    function Child4 () {
        Parent4.call(this)
        this.type = 'child1'
    }
    Child4.prototype=Parent4.prototype


    /*
    * 组合继承的优化2
    *
    * */
    function Parent5 () {
        this.name = 'parent1'
    }

    function Child5 () {
        Parent5.call(this)
        this.type = 'child1'
    }
    Child5.prototype=Object.create(Parent5.prototype)
    Child5.prototype.constructor=Child5

猜你喜欢

转载自blog.csdn.net/u013482875/article/details/82469937