对象创建模式
Object构造函数模式
先创建Object对象,再动态添加属性/方法
- 适用场景:起始时不确定对象内部数据
- 问题:语句太多
var p = new Object();
p.name = 'kk';
p.age = 20;
p.setName = function(name) {
this.name = name
};
p.setName('xx');
console.log(p.name, p.age); //xx 20
对象字面量模式
使用{}创建对象,同时指定属性/方法
- 适用场景:起始时对象内部数据时确定的
- 问题:语如果创建多个对象,有重复代码
var p = {
name: 'kk',
age: 20,
setName: function (name) {
this.name = name
}
}
p.setName('xx');
console.log(p.name, p.age); //xx 20
工厂模式
通过工厂函数动态创建对象并返回
- 适用场景:需要创建多个对象
- 问题:对象没有一个具体的类型,都是Object类型
function createPerson(name, age) {
var obj = {
name: name,
age: age,
setName: function (name) {
this.name = name
}
}
return obj
}
var p1 = createPerson('kk', 20)
var p2 = createPerson('xx', 21)
自定义构造函数模式
此定义构造函数,通过new创建对象
- 适用场景:需要创建多个类型确定的对象
- 问题:每个对象都有相同的数据,浪费内存
function Person(name, age) {
this.name = name,
this.age = age,
this.setName = function (name) {
this.name = name
}
}
var p1 = new Person('kk', 20)
p1.setName('xx')
console.log(p1.name, p1.age) //xx 20
console.log(p1 instanceof Person) //true
构造函数+原型的组合模式
自定义构造函数,属性在函数中初始化,方法添加到原型上
- 适用场景:需要创建多个类型确定的对象
function Person(name, age) {
this.name = name,
this.age = age
}
Person.prototype.setName = function (name) {
this.name = name
}
var p1 = new Person('kk', 20)
p1.setName('xx')
console.log(p1.name, p1.age) //xx 20
继承模式
原型链继承
- 定义父类型构造函数
- 给父类型的原型添加方法
- 定义子类型的构造函数
- 创建父类型的对象赋值给子类型的原型
- 将子类型原型的构造属性设置为子类型
- 给子类型原型添加方法
- 创建子类型对象:可以调用父类型的方法
关键:子类型的原型为父类型的一个实例对象
//父类型
function Supper() {
this.supProp = 'Super property'
}
Supper.prototype.showSupperProp = function () {
console.log(this.supProp)
}
//子类型
function Sub() {
this.subProp = 'Sub property'
}
//子类型的原型为父类型的一个实例对象
Sub.prototype = new Supper()
//让子类型的原型的constructor指向子类型
Sub.prototype.constructor = Sub
Sub.prototype.showSubProp = function () {
console.log(this.subProp)
}
var sub = new Sub()
sub.showSupperProp() // Super property
sub.showSubProp() // Sub property
借用构造函数继承
*关键:在子类构造函数中通过call()调用父类构造函数
function Person(name, age) {
this.name = name
this.age = age
}
function Dog(name, age, gender) {
Person.call(this, name, age)
this.gender = gender
}
var dog = new Dog('corgi', 1, 'male')
console.log(dog.name, dog.age, dog.gender) // corgi 1 male
组合继承
- 原型链+借用构造函数的组合继承
- 利用原型链实现对父类型对象的方法继承
- 利用super()借用父类型构造函数初始化同属性
function Person(name, age) {
this.name = name
this.age = age
}
Person.prototype.setName = function (name) {
this.name = name
}
function Student(name, age, gender) {
Person.call(this, name, age)
this.gender = gender
}
//子类型的原型为父类型的一个实例对象
Student.prototype = new Person()
//让子类型的原型的constructor指向子类型
Student.prototype.constructor = Student
Student.prototype.setGender = function (gender) {
this.gender = gender
}
var s = new Student('kk', 15, 'fmale')
s.setName('xx')
s.setGender('male')
console.log(s.name, s.age, s.gender) // xx 15 male