javascript 创建对象4种模式

工厂模式


function createPerson(name){
var o = new Object()
o.name = name
o.sayName = function(){
console.log(o.name)
}
}
var person = createPerson('js')

构造函数模式


function Person(name){
this.name = name
this.sayName = function(){
console.log(this.name)
}
}
var person = new Person('js')

原型模式


function Person(){
}
Person.prototype.name = 'nicholas'
Person.prototype.sayName = function(){
console.log(this.name)
}
var person = new Person('js')

构造函数和原型模式组合


function Person(name){
this.name = name
}
Person.prototype = {
constructor :Person,
sayName: function(){
console.log(this.name)
}
}
var person = new Person('js')

你可能感兴趣的:(javascript 创建对象4种模式)