一、工厂模式
- 工厂模式:软件工程领域一种广为人知的设计模式,这种模式抽象了创建具体对象的过程。如下:
<script>
//工厂模式
function fun(name,age,sex){
var obj = new Object();
obj.name = name;
obj.age = age;
obj.sex = sex;
obj.sayName = function(){
alert(this.name);
};
return obj;
}
var person = fun('tom',25,'M');
person.sayName();
console.log(person.name,person.age,person.sex);//tom 25 M
var person1 = fun('lucy',20,'F');
person1.sayName();
console.log(person1.name,person1.age,person1.sex);//lucy 20 F
</script>
- 上述,函数fun()能够根据接受的参数来构建一个包含所有必要信息的fun对象。可以无数次的调用这个函数,而每次它都会返回一个包含三个属性一个方法的对象。工厂模式虽然解决了创建多个相似对象的问题,但却没有解决对象识别的问题(即怎样知道一个对象的类型)。随着JS的发展,又一个新模式出现了。
二、构造函数模式
- ECMAScript 中的构造函数可用来创建特定类型的对象。像Object和Array这样的原生构造函数,在运行时会自动出现在执行环境中。此外,也可以创建自定义的构造函数,从而定义自定义对象类型的属性和方法。如下:
<script>
//构造函数模式
function Student(id,name,age,height){
this.id = id;
this.name = name;
this.age = age;
this.height = height;
this.say = function(){
alert(this.name+'身高为:'+this.height);
}
}
var stu1 = new Student(1001,'tom',17,165);
console.log(stu1.id,stu1.age);//1001 17
stu1.say();//tom身高为:165
var stu2 = new Student(1002,'lucy',16,150);
console.log(stu2.id,stu2.age);//1002 16
stu2.say();//lucy身高为:150
</script>
三、原型模式
<script>
//原型模式
function Student(){
}
Student.prototype.id = 1001;
Student.prototype.name = 'lili';
Student.prototype.age = 18;
Student.prototype.height = 170;
Student.prototype.say = function(){
alert(this.name+'身高为:'+this.height);
};
let stu1 = new Student();
stu1.say();//lili身高为:170
</script>
- 我们创建的每个函数都有一个prototype(原型)属性,这个属性是一个指针,指向一个对象,而这个对象的用途是包含可以由特定类型的所有实例共享的属性和方法。就是说,不必在构造函数中定义对象实例的信息,而是可以将这些信息直接添加到原型对象中。
- 我们可以通过对象实例访问保存在原型中的值,但却不能通过对象实例重写原型中的值。如下:
<script>
//原型模式
function Student(){
}
Student.prototype.id = 1001;
Student.prototype.name = 'lili';
Student.prototype.age = 18;
Student.prototype.height = 170;
Student.prototype.say = function(){
alert(this.name+'身高为:'+this.height);
};
let stu1 = new Student();
stu1.say();//lili身高为170
stu1.name = 'lucy';
console.log(stu1.name);//lucy
//重名属性只能更改当前实例的值
let stu2 = new Student();
console.log(stu2.name);//lili
//当前实例继承的name值并没有被stu1实例更改
</script>