OO in JS(3)

☆组合使用构造函数和原型模式

数组写在构造函数里,函数写在原型里

动态原型模式

构造函数中进行判断,来决定是否要在原型中加入函数

寄生构造函数模式

在构造函数中创建并返回一个Object,然后new(类似于工厂模式,会重写构造函数的返回值)

稳妥构造函数模式

工厂模式,直接通过函数使用初始化传参

1
2
3
4
5
6
7
8
9
function Person (name) {
let o = new Object()
o.sayName = function () {
console.log(name)
}
return o
}
let a = Person('Orion')
a.sayName() // Orion

借用构造函数

这以及之后的都跟继承相关

1
2
3
4
5
6
7
8
9
10
function Super () {
this.list = ['a','b','c']
}
function Sub () {
Super.call(this) // apply也可以
}
let a = new Sub()
a.list.push('d')
let b = new Sub()
b.list // ["a", "b", "c"]

☆组合继承(伪经典继承)

数组写在父类的借用构造函数里,函数写在原型里

原型式继承

用某个原型来创建对象 Object.create()

1
2
3
4
5
function object(o) {
function F() {}
F.prototype = o
return new F()
}

寄生式继承

工厂模式,在工厂函数里调用原型式继承

寄生组合式继承

这之后我已经有点懵逼了,留待以后再慢慢品味

1
2
3
4
5
function F(sub, super) {
let prototype = Object(super.prototype)
prototype.constructor = sub
sub.prototype = prototype
}