//构造函数法
var person2 = new Object();
person2.name = "Twoiko";
person2.age = 26;
person2.sayName = function(){
alert(this.name);
};
//alert(person2.name); //Twoiko
创建多个对象
//工厂模式
function createPerson(name,age){
var person = new Object();
person.name = name;
person.age = age;
person.sayName = function(){
alert(this.name);
};
return person;
}
var person = createPerson("Zeriko",24);
//person.sayName(); // Zeriko
var person3 = new Person("Thriko",27);
var person4 = new Person("Fouiko",28);
person3.sayName(); //Thriko
person4.sayName(); //Fouiko
//alert(person3.name);
//alert(person4.name);
//原型模式
function Person(){
}
Person.prototype = {
name:"Niko",
age:29,
sayName:function(){
alert(this.name);
}
};
var person = new Person();
person.sayName();
var person2 = new Person();
person2.sayName();
//组合使用 构造函数模式 和 原型模式
//创建自定义类型的最常见的方式
//构造函数模式用于定义特有的实例属性,而原型模式用于定义方法和共享的属性。
//结果是每个实例都会有自己的一份实力属性的副本,但同时又共享着对方法的应用
function Person(name,age){
this.name = name;
this.age = age;
this.friends = ["Shelby","Court"];
}
Person.prototype = {
constructor: Person,
sayName: function () {
alert(this.name);
}
};
var person1 = new Person("Niko",25);
var person2 = new Person("Miko",26);
person1.friends.push("Viko");
alert(person1.friends); //Shelby,Court,Van
alert(person2.friends); //Shelby,Court
alert(person1.friends===person2.friends);//false
alert(person1.sayName===person2.sayName);//true