js - several ways to create objects (factory mode, the constructor mode, prototype pattern)

Verbatim https://www.dazhuanlan.com/2019/08/26/5d62f8b594f10/


  • Factory Pattern
    • Practice: Internal create an object, not the object property assignment and return
    • Cons: problem solving acquaintance creating multiple objects, but can not identify the type of object that is created
  • Constructor mode
    • Method: directly to the properties and methods assigned to this subject, there is no return statement
    • Disadvantages: the object is not common methods and properties, every time an object is necessary to create a new memory, the performance beyond consumption
  • Prototype mode
    • Practice: adding attributes to objects through prototype
    • Disadvantages: Each instance sharing method attributes, object attributes modify instance affect other instances
  • And a combination mode constructor prototype pattern
    • Practice: Constructors mode for instance property is defined, and a common method for defining a prototype model
    • Constructors blended with the prototype, the more widely used
  • Dynamic prototype model
    • A method by examining whether there should be effective, needs to be initialized to determine whether a property of the original
  • Parasitic constructor mode ...

Foreword

js object-oriented first step is what? A: The object is created. There are many ways to create objects in our most commonly used is the object literal to create an object, var obj = {}you see that I would not create an object yet, why should I continue to learn how to do those wonderful? I think people deserve a single, multi-master to find some objects can only be good ha. Seriously, there are so many words on high-end, using an object literal create a single object, there is a significant drawback, use the same interface to create many objects, will generate a lot of duplicate code. To solve this problem, we need to know the following? These ways.

Factory Pattern

1
2
3
4
5
6
7
8
9
10
11
12
function (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')

Factory mode solves the problem of creating multiple similar object, but the type of problem identification method to identify objects created object is not resolved. Because are all Object, without discrimination, unlike Date, Array, etc., resulting in a model constructor

Constructor mode

1
2
3
4
5
6
7
8
9
10
function Person(name) {
this.name = name
this.showName = function() {
alert(this.name)
}
}
var p1 = new Person('haha')
p1.showName()
var p2 = new Person('hehe')
p2.showName()

We note, the Person () code in
addition to the createPerson () in the same section, there are the following differences:

  • Not explicitly create an object;
  • Directly assigned to the properties and methods of this object;
  • No return statement.

In addition, it should be noted that the function name Person using a capital letter P. By convention, the constructor should always with an
uppercase letter, rather than the constructor should be with a lowercase letter. This approach borrowed from other OO languages, mainly in order to
distinguish it from other functions in ECMAScript; because the constructor function itself, but it can be used to create objects.
To create a new instance of the Person, you must use the new operator. In this way, call the constructor will actually go through the following four
steps:

  1. Create a new object;
  2. The scope of the constructor assigns a new object (so this points to the new object);
  3. Executing code constructor (add properties for the new object);
  4. Returns a new object.

for example

1
2
3
4
5
6
7
8
9
function Person(name) {
this.name = name
this.showName = function() {
alert(this.name)
}
console.log(this)
}
new Person('haha')
Person('haha')

We find that when using New to call a function of time, this point will be different. In fact, New primarily made following these things, but just wrote the following about the behavior, not the internal source

1
2
3
4
5
6
7
8
9
10
11
function  Person ( name ) { var obj = {} // declare an empty object obj   obj._proto_ = Person.prototype // _proto_ properties of this object to point to the object constructor function of the prototype, so obj prototype object can call Person under all methods, where the prototype to know the conclusion, the following will speak.   Person.apply (obj) // apply the method used to make this point to the object obj this .name = name // object obj add properties, methods, this .showName = function (





) {
Alert ( the this .name)
} return obj // return the object }


There is a function of the structure model problem:

1
a Google AlertEND_LINK (p1showName == p2showName), // false to be

The two objects are not visible share a method , every new time, the system will create a new memory, the two objects each have their own sites, but they have the same functionality, not shared, certainly not what we want. So there is a next method, the prototype configuration mode == +> prototype pattern

Prototype mode

We created each function has a prototype(prototype) property, this property is a pointer to an object , and this object is the use of a specific type containing properties and methods shared by all instances . If literally to understand, that
it is the prototype of that object created by calling the constructor's prototype object instance. The benefits of using the prototype object is
to make all object properties and methods it contains examples of sharing. In other words, the information does not have to define objects in the example of the configuration function, but
the information can be added directly to the prototype object, as shown in the following example.

1
2
3
4
5
6
7
8
9
10
11
function Person(name) {
this.name = name
}
Person.prototype.showName = function() {
alert(this.name)
}
var p1 = new Person('haha')
p1.showName()
var p2 = new Person('hehe')
p2.showName()
alert(p1.showName == p2.showName) //true

Test is true, visible showName () method is shared, meaning that they share a memory, further said that they have references relationship, that you change showName p1 also affect showName p2, and the problems are the reason is that we rarely see someone alone mode where the prototype.

And a combination mode constructor prototype pattern

Create a custom type most common way is to use a combination of model and prototype constructors mode. The constructor is used to define the real mode
embodiments properties, while the prototype model is used to define methods and shared properties. As a result, each instance will have its own copy of an instance attribute,
but at the same time sharing with reference to a method to maximize the saving memory. In addition, this model also supports hybrid transmission parameters to the constructor
number; described two modes is set long.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function Person(name, age, job) {
this.name = name
this.age = age
this.job = job
this.friends = ['Shelby', 'Court']
}
Person.prototype = {
constructor: Person,
sayName: function() {
alert(this.name)
}
}
var person1 = new Person('Nicholas', 29, 'Software Engineer')
var person2 = new Person('Greg', 27, 'Doctor')
person1.friends.push('Van')
alert(person1.friends) //"Shelby,Count,Van"
alert(person2.friends) //"Shelby,Count"
alert(person1.friends === person2.friends) //false
alert(person1.sayName === person2.sayName) //true

在这个例子中,实例属性都是在构造函数中定义的,而由所有实例共享的属性 constructor 和方
法 sayName() 则是在原型中定义的。而修改了 person1.friends (向其中添加一个新字符串),并不
会影响到 person2.friends ,因为它们分别引用了不同的数组。

种构造函数与原型混成的模式,是目前在 ECMAScript 中使用最广泛、认同度最高的一种创建自定义类型的方法。可以说,这是用来定义引用类型的一种默认模式。

动态原型模式

有其他 OO 语言经验的开发人员在看到独立的构造函数和原型时,很可能会感到非常困惑。动态原型模式正是致力于解决这个问题的一个方案,它把所有信息都封装在了构造函数中,而通过在构造函数中初始化原型(仅在必要的情况下),又保持了同时使用构造函数和原型的优点。换句话说,可以通过检查某个应该存在的方法是否有效,来决定是否需要初始化原型。来看一个例子。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function Person(name, age, job) {
//属性
this.name = name
this.age = age
this.job = job
// 方法
if (typeof this.sayName != 'function') {
Person.prototype.sayName = function() {
alert(this.name)
}
}
}
var friend = new Person('Nicholas', 29, 'Software Engineer')
friend.sayName()

注意构造函数代码中 if 判断语句的部分。这里只在 sayName() 方法不存在的情况下,才会将它添加到原
型中。这段代码只会在初次调用构造函数时才会执行。此后,原型已经完成初始化,不需要再做什么修
改了。不过要记住,这里对原型所做的修改,能够立即在所有实例中得到反映。因此,这种方法确实可
以说非常完美。其中, if 语句检查的可以是初始化之后应该存在的任何属性或方法——不必用一大堆
if 语句检查每个属性和每个方法;只要检查其中一个即可。对于采用这种模式创建的对象,还可以使
用 instanceof 操作符确定它的类型。

1
2
3
4
5
6
7
8
9
function Person() {}
var friend = new Person()
Person.prototype = {
constructor: Person,
sayName: function() {
alert(this.name)
}
}
friend.sayName() //error

Parasitic constructor mode

….

Guess you like

Origin www.cnblogs.com/petewell/p/11410433.html