工厂模式
<!DOCTYPE html>
<html>
<head>
<title>Factory Pattern Example</title>
<script type="text/javascript">
function createPerson(name, age, job){
var o = new Object();//创建
//加工
o.name = name;
o.age = age;
o.job = job;
o.sayName = function(){
alert(this.name);
};
return o;
}
var person1 = createPerson("Nicholas", 29, "Software Engineer");
var person2 = createPerson("Greg", 27, "Doctor");
person1.sayName(); //"Nicholas"
person2.sayName(); //"Greg"
</script>
</head>
<body>
</body>
</html>
缺点:没有解决对象识别的问题(即怎么知道一个对象的类型)。
构造函数模式
像Object和Array这样的原生构造函数,在运行时会自动出现在执行环境中。
<!DOCTYPE html>
<html>
<head>
<title>Constructor Pattern Example</title>
<script type="text/javascript">
function Person(name, age, job){
this.name = name;
this.age = age;
this.job = job;
this.sayName = function(){
alert(this.name);
};
}
var person1 = new Person("Nicholas", 29, "Software Engineer");
var person2 = new Person("Greg", 27, "Doctor");
person1.sayName(); //"Nicholas"
person2.sayName(); //"Greg"
alert(person1 instanceof Object); //true
alert(person1 instanceof Person); //true
alert(person2 instanceof Object); //true
alert(person2 instanceof Person); //true
alert(person1.constructor == Person); //true
alert(person2.constructor == Person); //true
alert(person1.sayName == person2.sayName); //false
</script>
</head>
<body>
</body>
</html>
- 没有现实地创建函数
- 直接将属性和方法赋给了this对象
- 没有return语句
- 函数名开头大写,区别于其他函数,虽然也是函数,只不过可以用来创建对象而已。
要创建Person的新实例,必须使用new操作符。以这种方式调用构造函数实际上会经历以下四个步骤:
- 创建一个新对象 var newObj=new object();
- 将构造函数的作用域赋给新对象(因此this就指向了这个新对象Person.apply.(newObj))
- 执行构造函数中的代码(为这个新对象添加属性)
- 返回新对象