Factory mode, constructor mode and prototype mode

Face to face reflection 2021-05-03 18:19:54
factory mode constructor mode prototype


One 、 Factory mode

Factory mode belongs to creation mode , It provides the best way to create objects . We create an object inside the function , Give object properties and methods , And pass return Return this object

function createPerson(name, age, job) {
var o = new Object()
o.name = name
o.age = age
o.job = job
o.sayName = function() {
console.log(this.name)
}
return o
}
var person1 = createPerson('caoyuan', 25, 'Software engineer')
var person2 = createPerson('neil', 23, 'Software engineer')
console.log(person1) // {name: "caoyuan", age: 25, job: "Software engineer", sayName: ƒ}
console.log(person2) // {name: "neil", age: 23, job: "Software engineer", sayName: ƒ}
 Copy code 

Two 、 Constructor Pattern

The difference between construction mode and factory mode is that ;

  1. No explicit creation of objects
  2. Assign properties and methods directly to this object
  3. No, return object
function Person(name, age, job) {
this.name = name
this.age = age
this.job = job
this.sayName = function() {
console.log(this.name)
}
}
let person1 = new Person('caoyuan', 25, 'Software Engineer')
let person2 = new Person('neil', 23, 'Software engineer')
person1.sayName()
person2.sayName()
 Copy code 

Calling a constructor in this way actually goes through the following four steps

  1. Create an object
  2. Assign the scope of the constructor to the new object ( therefore this Just point to this object )
  3. Code that executes the constructor ( Add properties for this new object )
  4. Returns the object

Parasitic structural function model

The basic idea of this pattern is to create a function , This function only encapsulates the code of the object , Then return to the newly created object .

function Person(name, age, job) {
var o = new Object()
o.name = name
o.age = age
o.job = job
o.sayName = function() {
console.log(this.name)
}
return o
}
let friend = new Person('neil', 25, 'software Engineer')
friend.sayName() // neil
 Copy code 

That's an example , hold new Operator cast , This pattern is as like as two peas. . The constructor returns no value , The new object instance is returned by default , And add one at the end of the constructor return sentence , You can override the value returned when called to a constructor . The following example

function SpecialArray () {
// Create array 
var values = new Array()
// add value 
values.push.apply(values, arguments)
// Add method 
values.toPipedString = function() {
return this.join('|')
}
// Returns an array of 
return values
}
var color = new SpecialArray('1','2','3')
console.log(color.toPipedString()) // 1|2|3
 Copy code 

Safe constructor mode Secure object means that there is no public attribute , Methods are not referenced this The object of . Suitable for safe environment , Or prevent the data from being used when it should be changed

The safe pattern follows a pattern similar to the parasitic constructor , but There are two differences ;

  1. Instances that create new objects are not referenced this;
  2. Don't use new Operators call constructors
function Person(name, age, job) {
var o = new Object()
o.sayName = function() {
console.log(name)
}
return o
}
let person = Person('neil', 25, 'software Engineer')
person.sayName() // neil
 Copy code 

Scope safe constructors

 Through the code to introduce the scope of the security of the constructor
function Person(name, age, job) {
this.name = name
this.age = age
this.job = job
}
var person = Person('neil', 25, 'Softwate Engineer')
console.log(window.age) // 25
 Copy code 

Suppose you call it in this way ,this Point to window, Then the value will be in window Yes , So how can we solve this problem , Modify the code as follows

function Person(name, age, job) {
if (this instanceof Person) {
this.name = name
this.age = age
this.job = job
} else {
return new Person(name, age, job)
}
}
var person = Person('neil', 25, 'software Engineer')
console.log(window.age) // undefined
console.log(person.age) // 25
 Copy code 

adopt instanceof To judge the present this Whether it is person Example of , Now it seems that there is no problem , Let's assume that the constructor is used to steal the inheritance of the pattern and the prototype chain is not used , This inheritance may be destroyed

function Polygon(sides) {
if (this instanceof Polygon) {
this.sides = sides
this.getArea = function() {
return 0
}
} else {
return new Polygon(sides)
}
}
function Rectangle(width, heigth) {
Polygon.call(this, 2)
this.width = width
this.heigth = heigth
this.getArea = function () {
return this.width * this.heigth
}
}
let rect = new Rectangle(5, 10)
console.log(rect.sides) // undefined
 Copy code 

You'll find that ,rect.sides by undefined, Why? ,Polygon This instance is secure , however ,Rectangle China is through call To inherit Polygon Of sides attribute , This is because this Object is not Polygon Example , So a new one was created Polygon object ,Rectangle Not in China sides attribute . This problem can be solved by using a combination of prototype chains and parasitic patterns , The code is as follows

function Polygon(sides) {
if (this instanceof Polygon) {
this.sides = sides
this.getArea = function() {
return 0
}
} else {
return new Polygon(sides)
}
}
function Rectangle(width, heigth) {
Polygon.call(this, 2)
this.width = width
this.heigth = heigth
this.getArea = function () {
return this.width * this.heigth
}
}
Rectangle.prototype = new Polygon()
let rect = new Rectangle(5, 10)
console.log(rect.sides) // 2
 Copy code 

3、 ... and 、 Archetypal model

Every function we create has prototype attribute , This property is a pointer , Point to object , This object contains properties and methods that can be shared by all columns of a particular type .prototype The prototype object of the instance object created by calling the constructor .

 function Person() {
}
Person.prototype.name = 'caoyuan'
Person.prototype.age = '25'
Person.prototype.sayName = function() {
console.log(this.name)
}
let person1 = new Person()
let person2 = new Person()
person2.sayName()
person1.sayName()
console.log(person1.sayName == person2.sayName)
 Copy code 

Dynamic prototype pattern

It encapsulates all the information in the constructor , By initializing the prototype in the constructor , It also keeps the advantage of using constructors and prototypes at the same time

function Person(name, age, job) {
this.name = name
this.age = age
this.job = job
// Method 
if (typeof this.sayName != 'function') {
Person.prototype.sayName = function() {
console.log(this.name)
}
}
}
let person = new Person('neil', 25, 'Software Engineer')
person.sayName()
 Copy code 

Four 、 Use a combination of constructor mode and prototype mode

The most common way to create custom objects , It's a combination of constructor mode and prototype mode .

  1. The constructor pattern defines the properties of the instance
  2. Prototype patterns are used to define methods and shared properties
function Person(name, age, job) {
this.name = name
this.age = age
this.children = ['1', '2']
}
Person.prototype.sayName = function() {
console.log(this.name)
}
let person1 = new Person('caoyuan', 25, 'Software Engineer')
let person2 = new Person('neil', 23, 'Software Engineer')
person1.children.push('3')
console.log(person1.children) // Array [1,2,3]
console.log(person2.children) // Array [1,2]
console.log(person1.children === person2.children) // false
console.log(person1.sayName === person2.sayName) // true
 Copy code 
版权声明
本文为[Face to face reflection]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/05/20210503181827568J.html

  1. 浅谈 React 中的 XSS 攻击
  2. XSS attack in react
  3. 自学前端教程整理,附不容错过的前端100篇文章合集
  4. Self taught front-end tutorial collation, with a collection of 100 front-end articles that can not be missed
  5. 使用OpenTracing跟踪Go中的HTTP请求延迟
  6. Using opentracing to track HTTP request latency in go
  7. Encapsulating databinding allows you to write less than 10000 lines of code
  8. 03-HTML5标签-HTML5极速入门
  9. 03-html5 tag-html5 quick start
  10. LayUI - 极易上手拿来即用的前端 UI 框架
  11. Layui - easy to use front end UI framework
  12. Interpretation of lodash source code (1)
  13. Why is the first parameter of node family callback error?
  14. 报告:JavaScript 开发者达1380 万,C#超越 PHP,Rust 增长最快
  15. Report: Javascript developers reach 13.8 million, C surpasses PHP, and rust grows fastest
  16. 小白前端入门笔记(10),怎么设置网站内部的超链接?
  17. How to set up hyperlinks inside the website?
  18. Using node and socket to realize online chat room
  19. The core competitiveness of Vue: data bidirectional binding
  20. React configuration agent
  21. CSS layout
  22. Application scenario explanation of Vue dynamic component
  23. Redux learning notes 04 -- using multiple reducers to manage data
  24. After three months of typescript writing, what have I learned?
  25. Node family - what is a callback?
  26. React -- a simple implementation of render & create element
  27. JS learning simple usage of jquery
  28. Seamless love
  29. 小白前端入门笔记(12),设置哑链接
  30. Small white front-end entry notes (12), set dumb links
  31. Vue2. X opens composition API and TSX
  32. Interview record and thinking of social recruitment for one and a half years (Alibaba, Tencent, baidu offer)
  33. Flex learning notes
  34. The most essential closure article in the eastern hemisphere
  35. 2021-05-03 hot news
  36. Sword finger offer -- reverse order pair in array (JS Implementation)
  37. Working process of scaffold
  38. Use decorator mode to strengthen your fetch
  39. [JS] scope (Introduction)
  40. Employment information statistics network (interface document)
  41. Analysis of MVC
  42. [middle stage] please stay and join me in the backstage
  43. Understanding front end garbage collection
  44. [continuous update] front end special style implementation
  45. Flutter product analysis and package reduction scheme
  46. XPath positioning
  47. 前端开发css中的flex布局的使用
  48. The use of flex layout in front end development CSS
  49. JQuery核心函数和静态方法
  50. JQuery core functions and static methods
  51. Node family - understanding of blocking and non blocking
  52. 热点微前端Microfrontend的讨论:谷歌AdWords是真实的微前端
  53. Vue source code analysis (2) initproxy initialization proxy
  54. What's TM called react diff
  55. Summary of common front end data structure
  56. Useeffect in hooks
  57. [encapsulation 02 design pattern] Command pattern, share meta pattern, combination pattern, proxy pattern, strategy pattern
  58. Front end notes: virtual Dom and diff of vue2. X
  59. The best code scanning plug-in of flutter
  60. The simplest plug-in for rights management of flutter