1.使用工厂模式创建对象
function createObj(name,age,grade){ var obj=new Object(); obj.name=name; obj.age=age; obj.grade=grade; return obj}//调用console.log(createObj('Jessica',13,4)); //{name: "Jessica", age: 13, grade: 4}
2.使用构造函数模式创建
function Person(name,age,grade){ this.name=name; this.age=age; this.grade=grade;}//调用var person=new Person('Jessica',13,4);console.log(person) //{name: "Jessica", age: 13, grade: 4}
3.使用原型模式创建
function Person(){}Person.prototype.name="Jessica";Person.prototype.age=13;Person.prototype.grade=4;Person.prototype.frends=['Anna'];Person.prototype.sayName=function () { alert(this.name);};//调用var person1=new Person();console.log(person1); //输出{}console.log(person1.name); //输出"Jessica"console.log(person1.frends.push('Alex'));var person2=new Person();console.log(person2.frends); //["Anna","Alex"]console.log(person1.hasOwnProperty("name")); //falseperson1.name="Bob";console.log(person1.hasOwnProperty("name")); //true
4.组合使用构造函数模式和原型模式
function Person(name,age,grade){ //构造函数模式用于定义实例属性 this.name=name; this.age=age; this.grade=grade; this.friends=['Anna','Alex'];}Person.prototype={ //原型模式用于定义共享的方法和属性 constructor:Person, sayName:function(){ console.log(this.name); }}var person1 = new Person("Nicholas", 15, 5);var person2 = new Person("Greg", 16, 6);person1.friends.push('Jessica');console.log(person1.friends); //["Anna","Alex","Jessica"];console.log(person2.friends); //["Anna","Alex"];
5.动态原型模式
function Person(name,age,grade){ this.name=name; this.age=age; this.grade=grade; if(typeof this.sayName!='function'){ Person.prototype.sayName=function(){ console.log(this.name) } }}var person= new Person('Jessica',12,4);person.sayName(); //Jessicavar person1= new Person('July',12,4);person1.sayName(); //July
6.寄生构造函数模式
function SpecialArray(){ //创建数组 var values =new Array(); //添加值 values.push.apply(values,arguments); //添加方法 values.toPipedString=function(){ return this.join("****") } return values;}var colors =new SpecialArray('11','22','33');console.log(colors.toPipedString()); //"11****22****33"
7.稳妥构造函数模式
function Person(name,age,grade){ var o =new Object(); o.sayName=function(){ console.log(name); }; return o;}var friend=Person('Jessica',12,5);friend.sayName(); //Jessica
各种模式的优缺点如下图: