Home > Web Front-end > JS Tutorial > Summary of how to create objects in JavaScript (super classic)

Summary of how to create objects in JavaScript (super classic)

不言
Release: 2018-08-29 16:28:39
Original
1190 people have browsed it

This article brings you a summary of the way to create objects in JavaScript (super classic). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

There are many ways to create objects in JavaScript. You can also create a single object through the Object constructor or object literal. Obviously, these two methods will generate a lot of repeated code and are not suitable for mass production. Next, we will introduce seven very classic ways to create objects. They each have their own advantages and disadvantages. (The content mainly comes from "JavaScript Advanced Programming", and also referred to articles written by others)

1. Factory mode

function createPerson(name, job) { 
 var o = new Object() ;
 o.name = name ;
 o.job = job ;
 o.sayName = function() { 
  console.log(this.name) 
 } 
 return o 
} 
var person1 = createPerson('Mike', 'student') 
var person2 = createPerson('X', 'engineer')
Copy after login

This factory can be called countless times Function, each time returns an object containing two properties and one method.
Although the factory pattern solves the problem of creating multiple similar objects, it does not solve the problem of object identification, that is, it cannot know the type of an object.

2. Constructor mode

function Person(name, job) { 
 this.name = name ;
 this.job = job ;
 this.sayName = function() { 
  console.log(this.name) 
 } 
} 
var person1 = new Person('Mike', 'student') 
var person2 = new Person('X', 'engineer')
Copy after login

There is no displayed created object. Use new to call this constructor. After using new, the following operations will be automatically performed:
① Create a new object;
② Assign the scope of the constructor to the new object (so this points to the new object);
③ Execute the code in the constructor (add attributes to this new object);
④ Return the new object.
Disadvantages: Each method must be recreated on each instance.
It is really not necessary to create two Function instances that complete the same task. Moreover, with this object, there is no need to bind the function to a specific object before executing the code. It can be defined in this form:

function Person( name, age, job ){
    this.name = name;
    this.age = age;
    this.job = job;

    this.sayName = sayName;
}

function sayName(){
    alert( this.name );
}
Copy after login

In this way, the definition of the sayName() function can be Move outside the constructor. Inside the constructor, we set the sayName property to the global sayName function. In this case, since sayName contains a pointer to a function, the person1 and person2 objects can share the same sayName() function defined in the global scope.

This solves the problem of two functions doing the same thing, but a new problem arises: a function defined in the global scope can actually only be called by a certain object, which makes the global scope The domain is a bit of a misnomer. And more importantly: if the object needs to define many methods, then many global functions need to be defined. In this way, our customized reference type has no encapsulation at all.

These problems can be solved by using the prototype pattern.

3. Prototype mode

function Person() { 
} 
Person.prototype.name = 'Mike' 
Person.prototype.job = 'student' 
Person.prototype.sayName = function() { 
 console.log(this.name) 
} 
var person1 = new Person()
Copy after login

Add information directly to the prototype object. The advantage of using a prototype is that all instance objects can share the properties and methods it contains. Instead of defining object instance information in the constructor, this information can be added directly to the prototype object.
①Understanding the prototype
Whenever a new function is created, a prototype attribute will be created for the function according to a specific set of rules.
By default, all prototype attributes will automatically obtain a constructor (constructor) attribute, which contains a pointer to the function where the prototype attribute is located. pointer.
Every time the code reads a property of an object, a search is performed, targeting the property with the given name. The search starts with the object instance itself. If an attribute with the given name is found in the instance, the value of the attribute is returned; if not found, the prototype object pointed to by the pointer is searched and the attribute with the given name is found in the prototype object. If this property is found in the prototype object, the value of this property is returned.
Although the value stored in the prototype can be accessed through the object instance, the value in the prototype cannot be overwritten through the object instance.
If we add a property to the instance, and the property has the same name as a property in the instance, then the property will be created in the instance, and the property will block that property in the prototype.
Even if the property is set to null, only the property value in the instance is null.
However, using the delete operator can completely delete instance properties, allowing you to re-access the properties in the prototype.
Use the hasOwnProperty() method to detect whether a property exists in the instance or in the prototype. This method will return true only if the given property exists in the object instance.

②Prototype and in operator
The in operator will return true when a given property can be accessed through the object, regardless of whether the property exists in the instance or the prototype.

③Simpler prototype syntax

function Person(){    
}
Person.prototype = {
    name : "Mike",
    age : 29,
    job : "engineer",

    syaName : function(){
        alert( this.name );
    }
};
Copy after login

//In the above code, Person.prototype is set equal to a new object created in the form of an object literal. The end result is the same, with one exception: the constructor property no longer points to the Person.

4. Combined use of constructor pattern and prototype pattern

组合使用构造函数模式和原型模式是使用最为广泛、认同度最高的一种创建自定义类型的方法。它可以解决上面那些模式的缺点,使用此模式可以让每个实例都会有自己的一份实例属性副本,但同时又共享着对方法的引用,这样的话,即使实例属性修改引用类型的值,也不会影响其他实例的属性值了。还支持向构造函数传递参数,可谓是集两种模式的优点。

function Person(name) { 
 this.name = name 
 this.friends = ['Jack', 'Merry'] 
} 
Person.prototype.sayName = function() { 
 console.log(this.name) 
} 
var person1 = new Person() 
var person2 = new Person() 
person1.friends.push('Van') 
console.log(person1.friends) //["Jack", "Merry", "Van"] 
console.log(person2.friends) // ["Jack", "Merry"] 
console.log(person1.friends === person2.friends) //false
Copy after login

五、动态原型模式

动态原型模式将所有信息都封装在了构造函数中,初始化的时候。可以通过检测某个应该存在的方法是否有效,来决定是否需要初始化原型。

function Person(name, job) { 
  // 属性 
 this.name = name 
 this.job = job 
 // 方法 
 if(typeof this.sayName !== 'function') { 
  Person.prototype.sayName = function() { 
    console.log(this.name) 
  } 
 } 
} 
var person1 = new Person('Mike', 'Student') 
person1.sayName()
Copy after login

只有在sayName方法不存在的时候,才会将它添加到原型中。这段代码只会初次调用构造函数的时候才会执行。此后原型已经完成初始化,不需要在做什么修改了,这里对原型所做的修改,能够立即在所有实例中得到反映。
其次,if语句检查的可以是初始化之后应该存在的任何属性或方法,所以不必用一大堆的if语句检查每一个属性和方法,只要检查一个就行。

六、寄生构造函数模式

这种模式的基本思想就是创建一个函数,该函数的作用仅仅是封装创建对象的代码,然后再返回新建的对象

function Person(name, job) { 
  var o = new Object() 
 o.name = name 
 o.job = job 
 o.sayName = function() { 
  console.log(this.name) 
 } 
 return o 
} 
var person1 = new Person('Mike', 'student') 
person1.sayName()
Copy after login

这个模式,除了使用new操作符并把使用的包装函数叫做构造函数之外,和工厂模式几乎一样。
构造函数如果不返回对象,默认也会返回一个新的对象,通过在构造函数的末尾添加一个return语句,可以重写调用构造函数时返回的值。

七、稳妥构造函数模式

首先明白稳妥对象指的是没有公共属性,而且其方法也不引用this。稳妥对象最适合在一些安全环境中(这些环境会禁止使用this和new),或防止数据被其他应用程序改动时使用。
稳妥构造函数模式和寄生模式类似,有两点不同:1.是创建对象的实例方法不引用this;2.不使用new操作符调用构造函数

function Person(name, job) { 
 var o = new Object() 
 o.name = name 
 o.job = job 
 o.sayName = function() { 
  console.log(name) 
 } 
 return o 
} 
var person1 = Person('Mike', 'student') 
person1.sayName()
Copy after login

和寄生构造函数模式一样,这样创建出来的对象与构造函数之间没有什么关系,instanceof操作符对他们没有意义

相关推荐:

JavaScript的中对象创建和继承原理

javascript简单对象创建

The above is the detailed content of Summary of how to create objects in JavaScript (super classic). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template