对象/原型/继承

2019-05-07  本文已影响0人  jiangzj

对象属性

一、属性类型
ECMAScript 中有数据属性访问器属性两种属性,各有 4 个描述其行为的特征,其中两种属性都有的特性是:

数据属性 同时可具有:

访问器属性同时可具有:

需要注意的是,数据属性访问器属性不能同时存在
可以是用 Object.defineProperty或者Object.defineProperties来修改对象的属性,在使用这两个函数的时候,如果不指定,configurableenumerablewritable的默认值都为 false

原型

实例.__proto__ === 原型
原型.constructor === 构造函数
构造函数.prototype === 原型

原型链

每个对象都有 __proto__ 属性,指向了创建该对象的构造函数的原型,__proto__将对象连接起来组成了原型链,原型链可以用于实现继承共享属性

继承

一、原型链继承

    function Parent(age) {
        this.names = []
        this.age = age
    }

    Parent.prototype.foo = () => {}
    function Child() {}

    Child.prototype = new Parent()
    var child1 = new Child(5)
    var child2 = new Child(6)
    child1.names.push(1)
    child2.names.push(2)

二、构造函数

    function Parent(age) {
        this.names = []
        this.age = age
        this.foo = function () {}
    }

    function Child(age) {
        Parent.call(this, age)
    }

    var child = new Child(11)

三、组合继承

    function Parent(age) {
        this.name = 'Bill'
        this.age = age
    }
    Parent.prototype.foo = function () {}

    function Child(age) {
        Parent.call(this, age) //第二次调用构造函数
    }

    Child.prototype = new Parent() //第一次调用构造函数
    Child.prototype.constructor = Child
    var child = new Child(11)

四、原型式继承
与原型链类似

const objectCreate = (o) => {
    // 就是Object.create 静态方法的实现
    // 实际上只是对 o 进行了浅拷贝
    function F() {}
    F.prototype = o
    return new F()
}

五、寄生式继承
与借用构造函数类似

    function create(o) {
        var f = Object.create(o)
        f.foo = function() {}
        return f
    }

六、寄生组合式继承
主要是改进了组合继承需要调用两次构造函数的缺点

function object(o) {
    function F() {}
    F.prototype = o
    return new F()
}

// 这里代替了用来 组合式继承 第一次调用构造函数
// 将父类的原型进行一次浅拷贝
// 并将这个浅拷贝的对像作为原型链接到子类
function inheritPrototype(subType, superType) {
    var prototype = object(superType.prototype)
    prototype.constructor = subType
    subType.prototype = prototype
}

function SuperType(name) {
    this.name = name
    this.colors = ['red', 'blue']
}
SuperType.prototype.sayName = function() {
    alert(this.name)
}

function SubType(name, age) {
    SuperType.call(this, name)
    this.age = age
}
SubType.prototype.sayAge = function() {
    alert(this.age)
}

inheritPrototype(SubType, SuperType)
上一篇 下一篇

猜你喜欢

热点阅读