Web Front-end
JS Tutorial
Detailed explanation of how JavaScript objects are created and constructor pattern codeDetailed explanation of how JavaScript objects are created and constructor pattern code
javascript object-oriented knowledge is very extensive, and it will take some time to understand it in depth
Creation of objects:
1 Create an object-oriented
var obj = new Object();
obj.name = 'haha';
obj.showName = function(){
alert(obj.name);
}
obj.showName();Disadvantages: When we want to create multiple object-oriented objects, there are too many duplicate codes and need to be encapsulated, so there is a factory method.
2 Factory method
function CreatePerson(name){
var obj = new Object(); //原料
obj.name = name; //加工
obj.showName = function(){
alert(this.name);
}
return obj;//出厂
}
var p1 = CreatePerson('haha');
p1.showName();
var p2 = CreatePerson('hehe');
p2.showName();
//其实就是简单的封装函数,整个过程像工厂的流水线,所以叫工厂方式Disadvantages: The type of the created object cannot be identified. Because they are all Objects, there is no distinction, unlike Date, Array, etc., so the constructor pattern emerged.
3 Constructor pattern
function CreatePerson(name){
this.name = name;
this.showName = function(){
alert(this.name);
}
}
var p1 =new CreatePerson('haha');
p1.showName();
var p2 = new CreatePerson('hehe');
p2.showName();We change it through these two aspects:
The first letter of the function name is capitalized
This is to distinguish it from ordinary functions. The constructor itself is actually an ordinary function, but we use it specifically to implement the construction function, so we have a special name. Called a constructor, any function can become a constructor, depending on how you call the function. When called using New, it becomes a constructor.
New keyword call
The New keyword is used when calling the function, so what exactly does New do? What is the difference between using New or not? Looking at the following example
function CreatePerson(name){
this.name = name;
this.showName = function(){
alert(this.name);
};
console.log(this);
}
new CreatePerson('haha'); //CreatePerson
CreatePerson('haha'); //windowwe will find that when using New to call a function, the point of this will be different. In fact, New mainly does the following things, but what is written below is only a general behavior, not the internal source code.
function CreatePerson(name){
var obj = {}; //声明一个空对象obj
obj._proto_= CreatePerson.prototype;
//把这个对象的_proto_属性指向构造函数的原型对象,这样obj就可以调用CreatePerson原型对象下的所有方法 ,这里原型先知道结论,下面会讲。
CreatePerson.apply(obj); //用apply方法让this指向obj对象
this.name = name; //obj对象添加属性,方法
this.showName = function(){
alert(this.name);
};
return obj;//返回这个对象
}Problems with the function construction pattern:
alert(p1.showName==p2.showName);//false
Disadvantages: It can be seen that the two objects do not share one Method, every time new, the system will create a new memory. Each of these two objects has its own territory, but they have the same function and are not shared, which is definitely not what we want. So there is the next method, prototype + construction mode
4 Prototype + construction mode
Prototype: Each function has a prototype attribute, which is a Object, also called a prototype object, we can write methods and properties on it (but the prototype object not only has the properties and methods we wrote, but also others, which will be introduced below), and the instance created through this function Objects can share the methods and properties of this prototype object. So we only need to put the things we want to share under the prototype of the function, and the things we don't want to share can be created through the constructor.
Look at a chestnut (prototype + construction)
function CreatePerson(name){
this.name = name;
}
CreatePerson.prototype.showName = function(){
alert(this.name);
}
var p1 =new CreatePerson('haha');
p1.showName();
var p2 = new CreatePerson('hehe');
p2.showName();
alert(p1.showName==p2.showName);//trueThe test is true. It can be seen that the showName() method is shared, which means they share a memory. , furthermore, they have a reference relationship, which means that if you change the showName of p1, it will also affect the showName of p2.
The above is the detailed content of Detailed explanation of how JavaScript objects are created and constructor pattern code. For more information, please follow other related articles on the PHP Chinese website!
JavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AMJavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.
JavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AMThe main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.
Understanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AMUnderstanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.
Python vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AMPython is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.
Python vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AMPython and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.
From C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AMThe shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.
JavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AMDifferent JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.
Beyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AMJavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools

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

SublimeText3 Linux new version
SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.





