一、工厂模式
工程模式是一种比较简单的设计模式,主要用来创建对象用的
1、简单的工程模式
//1.简单的工程模式.html
代码语言:javascript复制<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function createPerson(name) {
var o = {}
o.name = name;
o.getName = function() {
console.log(this.name)
}
return o
}
var person1 = createPerson('zhangsan');
person1.getName()
console.log(person1.name)
</script>
</head>
<body>
</body>
</html>
2、工程模式实例
代码语言:javascript复制<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function Person(name) {
this.name = name
}
Person.prototype.getName = function () {
console.log(this.name)
}
function Car(model) {
this.model = model
}
Car.prototype.getModel = function() {
console.log(this.model)
}
function create(type, params) {
return new this[type](params)
}
create.prototype = {
person: Person,
car: Car,
}
var person1 = new create('person', 'zhangsan')
person1.getName()
/*
new create('person, 'zhangsan') -> {
__proto__: create.prototype
}
new this[type](params) = new Person('zhang san'); -> {
__proto__: Person.prototype,
name: 'zhangsan'
}
*/
// 如果不想要使用new进行工程创建对象
代码语言:javascript复制 function create(type, param) {
// instanceof 判断一个构造函数的prototype属性所指向的对象是否在另一个被检测对象的原型链上
// obj instanceof F
// 描述:obj.proto.proto… => F.prototype,沿着对象obj的原型链查找是否存在对象F.prototype,
// 若存在则返回true,若查找到原型链的终点Object.prototype仍未找到,则返回false。
if (this instanceof create) {
return new this[type](params)
} else {
return new create(type, param)
}
}
var car1 = create('car', 'benz');
car1.getModel()
</script>
</head>
<body>
</body>