1.工厂函数模式
function createPerson(name,age,gender) {
var p = {
name:name,
age:age,
gender:gender
}
return p
}
var cat = createPerson('tom',12,'male')
var dog = createPerson('lucy',10,'male')
console.log( cat.constructor ) //本质上来说还是手动创建,类型没办法细分。
console.log( cat.constructor == dog.constructor)
存放在构造函数的原型里,由同一个方法构建的。
2.构造函数模式
自定义构造函数,通过new调用构造函数(构造函数必须通过new来调用)
function Animal(name,age){
this.name = name;
this.age = age;
this.sayName = function(){//匿名函数,若函数保存在对象中,会造成内存的浪费,由于函数是公共的,所以放到公共位置上
console.log(this.name)
}
}
var dog = new Animal('tom',11)//每new一次,就开辟一片存储空间,浪费内存
var cat = new Animal('lucy',11)
console.log( cat.constructor == Animal)//true
console.log( cat instanceof Animal )//true
console.log( cat.sayName == dog.sayName)//false 不同的存储空间内的sayName,存储的位置不同
cat.sayName()
此处创建的对象构造函数是Animal,所以可以调用Animal原型当中的方法,所以类型就有了划分。
普通的对象构造函数是Object
3.构造函数 + 原型模式
将对象的私有特性存放在对象内存中,将对象可以共享属性保存到原型中
function Animal(name,age){
this.name = name
this.age = age
}
Animal.prototype.sayName = function(){
console.log(this.name)
}
var dog = new Animal('tom',11)
var cat = new Animal('lucy',11)
console.log( cat.sayName == dog.sayName)//true 存放的地址相同,都在Animal的原型上,构造函数的原型是公共的