Summary of how to create objects in JavaScript (super classic)
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')
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')
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 ); }
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()
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 ); } };
//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
五、动态原型模式
动态原型模式将所有信息都封装在了构造函数中,初始化的时候。可以通过检测某个应该存在的方法是否有效,来决定是否需要初始化原型。
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()
只有在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()
这个模式,除了使用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()
和寄生构造函数模式一样,这样创建出来的对象与构造函数之间没有什么关系,instanceof操作符对他们没有意义
相关推荐:
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Solution: 1. Check spelling and path; 2. Add reference to component; 3. Check registry; 4. Run as administrator; 5. Update or repair Office; 6. Check security software; 7. Use other versions Components; 8. View error messages; 9. Find other solutions. Detailed introduction: 1. Check spelling and path: Make sure there are no spelling errors in the name and path of the object, and the file does exist in the specified path; 2. Add references to components, etc.

How to use JS and Baidu Map to implement map pan function Baidu Map is a widely used map service platform, which is often used in web development to display geographical information, positioning and other functions. This article will introduce how to use JS and Baidu Map API to implement the map pan function, and provide specific code examples. 1. Preparation Before using Baidu Map API, you first need to apply for a developer account on Baidu Map Open Platform (http://lbsyun.baidu.com/) and create an application. Creation completed

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

Overview of how to use JS and Baidu Maps to implement map click event processing: In web development, it is often necessary to use map functions to display geographical location and geographical information. Click event processing on the map is a commonly used and important part of the map function. This article will introduce how to use JS and Baidu Map API to implement the click event processing function of the map, and give specific code examples. Steps: Import the API file of Baidu Map. First, import the file of Baidu Map API in the HTML file. This can be achieved through the following code:

How to use JS and Baidu Maps to implement the map heat map function Introduction: With the rapid development of the Internet and mobile devices, maps have become a common application scenario. As a visual display method, heat maps can help us understand the distribution of data more intuitively. This article will introduce how to use JS and Baidu Map API to implement the map heat map function, and provide specific code examples. Preparation work: Before starting, you need to prepare the following items: a Baidu developer account, create an application, and obtain the corresponding AP

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese
