当前位置:网站首页>Factory mode and constructor mode
Factory mode and constructor mode
2022-07-28 14:23:00 【Front cut zz】
Why use factory mode ?
Use Objec Constructors (var person = new Object();) Or object literal method (var person= {};) Can create a single object , But these methods have obvious shortcomings : Create many objects using the same interface , There's a lot of repetitive code . To solve this problem , We can use a variant of the factory pattern .
Factory mode
Factory mode is to create a function , Encapsulate the details of creating objects with specific interfaces with functions .
function createPerson(name,age){
var person=new Object();
person.name=name;
person.age=age;
person.info=function(){
alert(' Name is :'+this.name);
}
return person;
}
var per=createPerson('zs',27);
per.info();
function createPerson() Be able to build a... With all the necessary information based on the accepted parameters Person object .
You can call this function countless times , And each time an object containing two properties and one method is returned .
Although the factory mode solves the problem of multiple offset objects , But it doesn't solve the problem of object recognition ( That is, how to know the type of an object ).
Constructor Pattern
Constructors are used to create specific types of objects , image Object and Array The native constructor of , Appears automatically in the execution environment at run time .
Besides , You can also create a custom constructor , To define the properties and methods of custom object types .
for example , You can use the constructor pattern to rewrite the previous chestnut as follows :
function Person(name,age){
this.name=name;
this.age=age;
this.info=function(){
alert(' Name is :'+this.name);
}
return person;
}
var person1=new Person('zs',27);
var person2=new Person('ls',30);
person.info();
Among the chestnuts mentioned above ,Person() To replace the createPerson() function . There are great similarities between the two , There are also differences .
There are mainly :
1. Objects are not explicitly created
2. Assign properties and methods directly to this
3. No, return sentence
Besides , It should also be noted that Person Your name is capitalized P. This is the Convention , Constructors should always start with a capital letter , To distinguish non constructors .
Similar ones java Species class class , Also start with a capital letter .
I understand it , The constructor is equivalent to creating a class class , Create an instance , Just use new establish , This way of creating instances , More like es6 Of class.
All in all , The constructor itself is a function , It can only be used to create objects .
To create a Person New examples , You have to use new The operator . Call the constructor in this way , In fact, there will be the following 4 A step .
1. Create a new object
2. Assign the scope of the constructor to the new object ( therefore this It points to this new object )
3. Execute code in constructor ( Add properties for this new object )
4. Return to new object
In the last chestnut ,person1 and person2 Belong to different objects , Save different instances . Both objects have one constructor( Constructors ) attribute , This property points to Person
person1.constructor===Person;//true
person2.constructor===Person;//true
person1 instanceof Object ;//true
person1 instanceof Person ;//true
person2 Empathy ;
Creating a custom constructor means that its instance table can be treated as a specific type in the future ; And that's where the constructor pattern outperforms the factory pattern .
In this chestnut ,person1 and person2 The reason is Object Example , Because all objects inherit from Object.
Characteristics of constructor pattern
The only difference between constructors and other functions , The difference lies in the way of calling . Any function , As long as through the new Operator to call , It can be used as a constructor ;
If any function fails new Operator to call , Then he is no different from ordinary functions
such as , We can put in the chestnut Person Constructors call in any way .
// As constructors
var per1=new Person('ww',23)
console.log(per1.name);//'ww'
per1.info();// Name is :ww
// Execute as a normal function , Properties and methods have been added to window/global
Person('ww',23);
window.info();// Name is :ww
// Execute in the scope of another object
var user=new Object();
Person.call(user,'ww',23);
user.info();// Name is :ww
Constructor problem
The main problem with using constructors is that each method needs to be recreated every time an instance is created .
In the chestnuts above person1 and person2 There is one. info Methods , When these two methods are not the same Function example .
Because in ECMAScript Functions in are also objects , So every function defined , That is, an object is instantiated . In fact, it is equivalent to this definition :
function Person(name,age){
this.name=name;
this.age=age;
this.info=new Function(){
console.log(' Name is '+this.name)}
}
Functions created in this way , It will lead to different scope chains and identifier resolution , But create Function The mechanism for the new instance is still the same .
therefore , Functions with the same name on different instances are not equal
person1.info===person2.info;//false
here , We can think about , Whether it can realize the same function info Method to extract , Encapsulated outside the constructor ? We can do this
function Person(name,age){
this.name=name;
this.age=age;
this.info=info;
}
function info(){
console.log(this.name);
}
here , Let's put the function info Defined outside the constructor , Inside the constructor , We will info Attribute is equal to info.
because info Contains a pointer to a function , therefore perso1 and person2 Share the same under the overall effect info() function .
But the problem is : Methods under global scope , You can't just let an object call , Otherwise, it will be a bit untrue , We can use prototype patterns to solve these problems :
How does the prototype pattern solve the problems of constructors
The function to be created in the constructor , Put it into the prototype object to store , That's it Global variable pollution and The code structure is chaotic The problem of . The principle used here is : Members in the prototype object of the constructor , Can be accessed by the object created by this constructor , and , All objects share this object . See the following example :
function Person(name,age) {
this.name = name;
this.age = age;
}
var p = new Person("Tom",18);
var p1 = new Person("Adam",19);
Person.prototype.sayHello = function () {
console.log("Hello,this is" + this.name);
}
Person.prototype["sing"] = function () {
console.log("abc");
}
p.sayHello(); //Hello,this is Tom
p1.sayHello(); //Hello,this is Adam
p.sing(); //abc
p1.sing();
边栏推荐
猜你喜欢

如何有效进行回顾会议(上)?

Forage QR code -- online QR code generator

83.(cesium之家)cesium示例如何运行

Revised version | target detection: speed and accuracy comparison (faster r-cnn, r-fcn, SSD, FPN, retinanet and yolov3)

ZABBIX distributed
![[ecmascript6] other new interface features](/img/da/377f93d83b6722bf250d270e4eea28.png)
[ecmascript6] other new interface features

QQ robot configuration record based on nonebot2

一文读懂如何部署具有外部数据库的高可用 K3s

Clickhouse分布式集群搭建

手机滚动截屏软件推荐
随机推荐
Power amplifier and matching network learning
These three online PS tools should be tried
Development and definition of software testing
Nport serial server configuration website (whether the serial server is from network port to serial port)
牛客多校-Link with Level Edito I-(线性dp)
[translation] how to choose a network gateway for your private cloud
如何有效进行回顾会议(上)?
QML picture preview
Open source project - taier1.2 release, new workflow, tenant binding simplification and other functions
IP黑白名单
Docker deploys Mysql to realize remote connection [easy to understand]
83.(cesium之家)cesium示例如何运行
jenkins
LeetCode 105.从前序与中序遍历序列构造二叉树 && 106.从中序与后序遍历序列构造二叉树
[leetcode] 1331. Array sequence number conversion
这3款在线PS工具,得试试
超好用的手机录屏软件推荐
[server data recovery] HP StorageWorks series server RAID5 offline data recovery of two disks
【Utils】ServletUtil
深度学习基础----GNN谱域和空域 (不断完善更新积累)