美文网首页
三种方法创建对象

三种方法创建对象

作者: 大笑一声 | 来源:发表于2017-08-24 10:42 被阅读0次

字面量创建对象(模块化开发)

//缺点:使用字面量和new创建多个相同属性和方法的对象时,会产生大量的重复代码工厂模式可以解决

var person={

name:“张国宝”,

say:function(){

console.log(this.name);

}

}

new创建对象:

var person1=new Object();

person1.name="张国宝";

person1.say=function(){

console.log(this.name);

}

工厂模式创建对象(封装成一个对象函数):

function createPerson(name,age){

var obj=new Object();

obj.name=name;

obj.age=age;

obj.say=function(){

console.log(this.name);

   }

return obj;

}

var p1=createPerson('张国宝',18);

var p2=createPerson("小明",56);

p1.say();

p2.say();

构造函数创建对象:

function Person(name,age){

this.name=name;

this.age=age;

this.say=function(){

 console.log(this.name);

}

}

,var arr=new Person('hello',12);

arr.say();

相关文章

网友评论

      本文标题:三种方法创建对象

      本文链接:https://www.haomeiwen.com/subject/zwusdxtx.html