search
HomeWeb Front-endJS TutorialUnderstand JavaScript object creation and object creation through prototypes


1. Several ways to create objects

1. Independent declaration mode

var box1 = new Object();	//声明第一个对象并给各属性赋值
box1.name = 'Lee';
box1.age = 100;
box1.run = function () {
	return this.name + this.age + '运行中...';
};
alert(box.run());

var box2 = new Object();	//声明第二个对象并给属性赋值
box2.name = 'Jack';
box2.age = 200;
box2.run = function () {
	return this.name + this.age + '运行中...';
};
alert(box2.run());

At this time, box2 and box1 are independent of each other. will be confused.

But in this way, every time you declare an object with the same structure, you have to add a piece of code, which is particularly inconvenient, so we have the following factory pattern.

2. Factory mode

function createObject(name, age) { //集中实例化的函数
	var obj = new Object();
	obj.name = name;
	obj.age = age;
	obj.run = function () {
		return this.name + this.age + '运行中...';
	};
	return obj;
}

In this way, you only need to call the createObject() method every time you create a new object. At the same time, you can also pass parameters to initialize the object.
But since the objects produced by new are all subordinate to Object, when I want to make some distinctions in the nature of the objects produced by new, it will not work. At this time, there is a simpler constructor mode.

3. Constructor pattern

function Box(name, age) {
	this.name = name;
	this.age = age;
	this.run = function () {
		return this.name + this.age + '运行中...';
	};
}
var box1 = new Box('Lee', 100);
var box2 = new Box('Jack', 200);
alert(box1.run());
alert(box1 instanceof Box); //很清晰的识别他从属于Box

The constructor pattern largely solves the problem of object reuse and parameter initialization, and is the most commonly used new object pattern.
Note:

Herebox1.run != box2.run, because they determine the reference address, so It can be seen that the methods of the two objects are stored in different places and are two different methods.
But box1.run() == box2.run(), because they return the same value.
When you have an object, it will naturally involve the sharing of object attributes and methods (for example, in Java, subclasses share member variables and methods of the parent class).
To put it bluntly, the objects created by the constructor pattern are independent of each other (such as box1.run != box2.run above). If I want to share certain attributes between two objects, I must use a prototype. prototype.

2. Create objects through prototypes

1. Prototype mode

function Box() {} //声明一个构造函数
Box.prototype.name = 'Lee'; //在原型里添加属性
Box.prototype.age = 100;
Box.prototype.arr = ['aaa','bbb'];
Box.prototype.run = function () { //在原型里添加方法
	return this.name + this.age + '运行中...';
};
var box1 = new Box();
var box2 = new Box();

//修改普通属性,看下会不会影响prototype
alert(box1.name);	//Lee
box1.name = 'Rinima';
alert(box1.name);	//Rinima
alert(box2.name);	//Lee,修改box1的普通属性,相当于直接在box1中添加一个属性,是不会牵扯到原型中的属性的。
					//这一点非常好。但是如果是引用对象(数组)的话,就有问题了。

//修改引用属性,看下会不会影响prototype
alert(box1.arr);	//aaa,bbb
box1.arr.push('ccc');
alert(box1.arr);	//aaa,bbb,ccc
alert(box2.arr);	//aaa,bbb,ccc,修改box1的引用属性,却牵扯到了原型中的属性。
			//这是因为arr只是个引用地址,指向数组真实存储的位置,修改box1中的引用属性就是修改引用所指向的数组,所以原型也被修改了
			//这是我们不希望看到的!

Advantages of this mode:

1. The properties of the new object in the prototype are shared. At this time, box1.run == box2.run
2, it can ensure that the properties of the new object instance are completely unified. (Compared to Disadvantage 2)
Disadvantages of this mode:

1. When there is an attribute of a reference type, the attribute pointed to by the reference type does not exist. In the prototype, directly modifying the reference properties in the object will modify the reference properties of all objects
2. This mode omits the initialization parameter transfer, so that all properties of new are the same.

1.1. Prototype literal mode

(Another mode of prototype mode, generally there is not much difference, both belong to prototype mode)

function Box() {};
Box.prototype = { //使用字面量的方式
	constructor : Box,
	name : 'Lee',
	age : 100,
	run : function () {
		return this.name + this.age + '运行中...';
	}
};

This mode inherits all the advantages and disadvantages of the prototype mode, but it also has its own unique advantages and disadvantages
Advantages: Better reflects the encapsulation
Disadvantages: The constructor does not point to itself and must be manually forced to point

2. Constructor + prototype mode

function Desk(name, age) { //不共享的使用构造函数
	this.name = name;
	this.age = age;
	this.family = ['aaa', 'bbb', 'ccc'];
};
Desk.prototype = { //共享的使用原型模式
	constructor : Desk,
	run : function () {
		return this.name + this.age + this.family;
	}
};

var desk1 = new Desk('Lee',100);
var desk2 = new Desk('Jack',200);
alert(desk1.family);	//aaa,bbb,ccc
desk1.family.push('ddd');
alert(desk1.family);	//aaa,bbb,ccc,ddd
alert(desk2.family);	//aaa,bbb,ccc

Advantages: This mode It perfectly solves the problem of shared attributes and non-shared attributes, and can be precisely controlled. It is a very good model.
Disadvantages: However, in this method, the prototype and the constructor are separated, which makes people feel weird and does not reflect encapsulation.

3. Dynamic prototype mode

function Box(name ,age) { //将所有信息封装到函数体内
	this.name = name;		//不共享的属性
	this.age = age;
	
	if (typeof this.arr != 'object') {		//共享的属性
		alert('在第一次调用的时候...arr');
		Box.prototype.arr = ['aaa','bbb'];
	}
	if (typeof this.run != 'function') {
		alert('在第一次调用的时候...run');
		Box.prototype.run = function () {
			return this.name + this.age + '运行中...';
		};
	}
}
var box1 = new Box();
var box2 = new Box();
alert( box1.arr );		//aaa,bbb
box1.arr.push('ccc');
alert( box1.arr );		//aaa,bbb,ccc
alert( box2.arr );		//aaa,bbb


Advantages: This mode inherits all the advantages of the previous mode (construction + prototype), and also perfectly solves the encapsulation problem
Note: Literal mode cannot be used when writing prototypes in this mode, which will cut off the connection between the instance and the new prototype. ? ? ?

At this point, the above two modes can already handle most problems, and they are better modes.
However, there are still some specific needs that require the use of the following two alternative modes.


4. Parasitic constructor pattern (factory pattern + constructor pattern)

function Box(name, age) {
	var obj = new Object();
	obj.name = name;
	obj.age = age;
	obj.run = function () {
		return this.name + this.age + '运行中...';
	};
	return obj;
}

5. Safe constructor pattern

function Box(name , age) {
	var obj = new Object();
	obj.run = function () {
		return name + age + '运行中...'; //直接打印参数即可
	};
	return obj;
}

Sure constructor mode is a mode that needs to be used when this is not allowed to be used in the constructor and new is not allowed to be used during external instantiation.
I don’t know why there is such a strange demand. However, so many object creation patterns are indeed much more dazzling than Java.

The above is the detailed content of Understand JavaScript object creation and object creation through prototypes. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript'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 CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The 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 DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding 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 UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python 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 ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python 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 WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The 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 ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different 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 WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript'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.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.