JavaScript创建对象的六种方法
字面量方式(很常用)
var person = {
name: "linyouyou",
age: 22,
say: function() {
alert(this.name)
}
}
var person2 = {}
person2.name: "zhangsan"
person2.age: 26
person2.say: function() {
alert(this.name)
}
new 操作符 + Object () 方法
var person = new Object()
person.name = "linyouyou"
person.age = 22
person.say = function() {
alert(this.name)
}
以上两种方法在使用同一接口创建多个对象时,会产生大量重复代码,所以产生了工厂模式
工厂模式
function createPerson(name,age) {
var p = new Object()
p.name = name
p.age = age
p.say = function() {
alert(this.name)
}
return p
}
工厂模式解决了重复实例化多个对象的问题,但没有解决对象识别的问题
构造函数模式
构造函数模式解决了对象识别问题
function Person(name,age) {
this.name = name
this.age = age
this.say = function(){
alert(this.name)
}
}
var person1 = new Person("linyouyou",22)
var person2 = new Person("zhangsan",26)
console.log(person1 instanceof Object) // true
console.log(person1 instanceof Person) // true
console.log(person2 instanceof Object) // true
console.log(person2 instanceof Person) // true
console.log(person1.constructor) // constructor 属性返回对创建此对象的数组、函数的引用
使用 new 来调用函数,或者说发生构造函数调用时,new 操作符会自动执行四步操作
- 在内存中创建(或者说构造)一个全新的对象
- 这个新对象会绑定到函数调用的 this (new 会让 this 指向这个新的对象)
- 将新对象的原型指针指向构造函数的原型 Prototype(设置属相和方法的值)
- 如果函数没有返回其他对象,那么 new 表达式中的函数调用会自动返回这个新对象(所以构造函数里面不需要 return )
原型模式
function Person() {}
Person.prototype.name = "linyouyou"
Person.prototype.age = 22
Person.prototype.say = function(){
alert(this.name)
}
console.log(Person.prototype) //Object{name: 'linyouyou', age: 22}
var person1 = new Person() //创建一个实例person1
console.log(person1.name) //linyouyou
var person2 = new Person() //创建实例person2
person2.name = "xuhuanshan"
person2.family = ["gujia","xuziyan"]
console.log(person2) //Person {name: "xuhuanshan",age: 22, family: Array[2]}
console.log(person2.prototype.name) //报错
console.log(person2.age) //22
混合模式(构造函数模式+原型模式)
构造函数模式用于定义实例属性,原型模式用于定义方法和共享的属性,混合模式共享着对相同方法的引用,又保证了每个实例有自己的私有属性。最大限度的节省了内存
function Person(name,age){
this.name = name
this.age = age
}
Person.prototype = {
constructor: Person, // 每个函数都有prototype属性,指向该函数原型对象,原型对象都有constructor属性, 这是一个指向prototype属性所在函数的指针
say: function() {
alert(this.name)
}
}
var person1 = new Person("linyouyou",22)
console.log(person1)
var person2 = new Person("zhangsan",26)
console.log(person2)