javascript 创建对象4种模式

工厂模式

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

构造函数模式

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

原型模式

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

构造函数和原型模式组合

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容