search
HomeWeb Front-endJS TutorialJavaScript's object-oriented approach can be implemented without using the constructor (Constructor) new keyword_javascript tips

The object model in JavaScript is not widely known. I once wrote a blog about them. One of the reasons why it is not well known is that JavaScript is the only one of these widely used languages ​​​​that implements inheritance through prototypes. However, I think another reason is that this object model is very complex and difficult to explain. Why is it so complex and confusing? That's because JavaScript tries to hide its traditional object-oriented characteristics - ultimately leading to its dual personality (Translator's Note: The author means that JavaScript has both process-oriented and object-oriented characteristics).

I think it is precisely because of the difficulty of understanding and using the JavaScript object model that there are languages ​​like CoffeeScript, Dart and TypeScript that can generate JS code through compilation.

JavaScript’s predecessors and die-hards believe that JavaScript has a better object model and lament that it will be forgotten by everyone. Even JavaScript expert Nicholas Zakas welcomes the new class syntax added in ECMAScript 6 - which is just a modification of the prototypal style syntax. In other words, traditional OOP wins.

A bold idea
However, let us make an idea in a joking way: we imagine traveling to the past, when traditional object-oriented programming was not as good as it is now. This is widely accepted by everyone. On the contrary, the prototype-based inheritance model has been widely accepted by everyone. What will happen? What design patterns will we end up with?

Let’s imagine again: What would happen if JavaScript had no constructor or no new keyword? What will happen next? Let's push back to the past. :)

First of all, the first thing, in JavaScript, we can use object literals to create a new object. As shown below:

Copy the code The code is as follows:

var felix = {
name : 'Felix',
greet: function(){
console.log('Hello, I am ' this.name '.');
}
};

Next, suppose we want to generalize the greet function, extract it and put it in a general location, so that we can create multiple objects to share the same greet method. How to achieve this?
We have several options, let’s start with mixin.

1. Mixin(Augmentation)
In JavaScript language, mixing attributes is very simple. You just need to copy the properties of the mixed object to the object you want to mix in. We will use an "augment" function to implement it, you will understand by looking at the code:
Copy the code The code is as follows:

var Dude = {
greet: function(){
console.log('Hello, I am ' this.name '.')
}
};
var felix = { name: 'Felix' };
augment(felix, Dude);//Copy the attributes in Dude to felix, that is, mixin

In the above code, the augment function mixes the properties of the Dude object into felix. In many JS libraries, the augment function is called extend. I don't like using extend because some languages ​​use extend to express inheritance, which makes me confused. I prefer to use "augment" to express it, because in fact this approach is not inheritance, and the syntax augment(felix, Dude) already clearly shows that you are extending felix with the attributes in Dude, rather than inheriting.

Maybe you have already guessed that the augment code is implemented, yes, it is very simple. As shown below:
Copy code The code is as follows:

function augment(obj, properties){
for (var key in properties){
obj[key] = properties[key];
}
}

2. Object Cloning )
An alternative to mixin is to clone the Dude object first, and then set the name attribute to the cloned object. As shown below:
Copy code The code is as follows:

var Dude = {
greet : function(){
console.log('Hello, I am ' this.name '.');
}
}
var felix = clone(Dude);//Clone the Dude object
felix.name = 'Felix';

The only difference between the two methods is the order in which the properties are added. You may consider using this technique if you want to override certain methods in the cloned object.
Copy code The code is as follows:

var felix = clone(Dude);
felix .name = 'Felix';
felix.greet = function(){
console.log('Yo dawg!');
};//Override greet method

If you want to call the method of the parent class, it is also very simple - use the apply function, as shown below
Copy the code The code is as follows:

felix.greet = function(){
Dude.greet.apply(this);
this.greetingCount ;
}

This is much better than prototype-style code because you don’t have to use the .prototype property of the constructor - we won’t use any constructors.
The following is the implementation of the clone function:
Copy code The code is as follows:

function clone (obj){
var retval = {};//Create an empty object
augment(retval, obj);//Copy attributes
return retval;
}

3. Inheritance
Finally, it is inheritance. Inheritance is overrated in my opinion, but inheritance does have some advantages over object expansion in terms of sharing properties between "instance objects". Let's write an inherit function that takes an object as a parameter and returns a new object that inherits from that object.
Copy code The code is as follows:

var felix = inherit(Dude);
felix .name = 'Felix';

Using inheritance, you can create multiple child objects that inherit from the same object. These child objects can inherit the properties of the parent object in real time. As shown in the code below,
Copy code The code is as follows:

var garfield = inherit( Dude);//garfield inherits from Dude
Dude.walk = function(){//Add a new method to Dude walk
console.log('Step, step');
};
garfield.walk(); // prints "Step, step"
felix.walk(); // also prints "Step, step"

Prototype-based is used in the inherit function Inheritance of objects
Copy code The code is as follows:

function inherit(proto){
if (Object.create){
//Use the Object.create method in ES5
return Object.create(proto);
}else if ({}.__proto__){
//Use Non-standard attribute __proto__
var ret = {};
ret.__proto__ = proto;
return ret;
}else{
//If neither is supported, use the constructor Inherit
var f = function(){};
f.prototype = proto;
return new f();
}
}

the above The code doesn't look good, that's because we use feature monitoring to determine which of the 3 methods to use.

But, how to use the constructor method (that is, the initialization method)? How do you share initialization code between instance objects? In some cases, if you only need to set some properties for the object, then the initialization function is not necessary, as in our example above. But if you have more initialization code, you might make a convention, for example: use an initialization method called initialize. We assume that a method called initialize is defined in Dude, as follows:
Copy the code The code is as follows:

var Dude = {
initialize: function(){
this.greetingCount = 0;
},
greet: function(){
console.log('Hello, I am ' this.name '.');
this.greetingCount ;
}
}

Then, you can initialize the object like this
Copy code The code is as follows:

var felix = clone(Dude);
felix.name = 'Felix';
felix.initialize(); or
var felix = { name: 'Felix' } ;
felix.name = 'Felix';
augment(felix, Dude);
felix.initialize();Also
var felix = inherit(Dude);
felix.name = 'Felix';
felix.initialize();Conclusion

I mean that through the three functions defined above - augment, clone and inherit, you can do anything with objects in JavaScript What you want to do without having to use constructors and the new keyword. I think the semantics embodied by these three functions are simpler and closer to the underlying object system of JavaScript. (End)^_^
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
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

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.

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

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools