Home Web Front-end JS Tutorial Explanation of using constructor to create objects in JavaScript without new_javascript tips

Explanation of using constructor to create objects in JavaScript without new_javascript tips

May 16, 2016 pm 05:55 PM
new Create object

As follows

Copy code The code is as follows:
function Person(name, age) {
this.name = name;
this.age = age;
}
var p = new Person('lily', 20);


Discover something It's strange how the library code creates regular objects without using new. As follows
Copy codeThe code is as follows:
var reg = RegExp('^he$');


The test found that whether new is used or not, the final returned objects are regular objects, and typeof them are all "object".
Copy code The code is as follows:
var reg1 = new RegExp('^he$');
var reg2 = RegExp('^he$');
reg1.test('he'); // true
reg2.test('he'); // true
console.log( typeof reg1); // object
console.log(typeof reg2); // object


Well, pretty good, the code runs normally.
If this is the case, just don’t write new at all, which will save the amount of code. Is this true for other types as well? Try String/Number/Boolean.
Copy code The code is as follows:
var str1 = new String(1);
var str2 = String(1);
var num1 = new Number('1');
var num2 = Number('1');
var boo1 = new Boolean(1);
var boo2 = Boolean(1);
console.log(typeof str1); // object
console.log(typeof str2); // string
console.log(typeof num1); // object
console.log(typeof num2); // number
console.log(typeof boo1); // object
console.log(typeof boo2); // boolean


As you can see, it is different from the regular case. Regularly, regardless of whether it is new or not, typeof is followed by object.
But for String/Number/Boolean types, the new object typeof returns "object", and the non-new typeof returns "string".
That is, if new is not applicable, other types can be converted into string, number and Boolean types respectively.

Okay, let’s go back to the Person class at the beginning of the chapter. That is, can the classes we write ourselves generate objects without using the new operator?
Copy code The code is as follows:
function Person(name, age) {
this.name = name;
this.age = age;
}
var p = Person('lily', 20);
console.log(p); // undefined


returns undefined, which is obviously not possible. Therefore, it is fanciful to create a Person instance without using new.
What if it has to be realized? In fact, it works, as follows
Copy the code The code is as follows:
function Person(name, age) {
this.name = name;
this.age = age;
if (this===window) {
return new Person(name, age);
}
}
var p = Person('lily', 20); // object


slightly modified the Person class. In fact, it is distinguished internally whether Person is executed as a constructor or a function.
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the problem that activex components cannot create objects How to solve the problem that activex components cannot create objects Jan 24, 2024 pm 02:48 PM

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 create objects using Java reflection mechanism? How to create objects using Java reflection mechanism? Apr 15, 2024 pm 04:18 PM

The steps to create an object through the Java reflection mechanism are as follows: Load the target class: Use the Class.forName() method. Get the constructor: use the getDeclaredConstructor() method. Create an object: Use the newInstance() method to pass parameters.

How to use the new keyword in java How to use the new keyword in java May 03, 2023 pm 10:16 PM

1. Concept In the Java language, the "new" expression is responsible for creating an instance, in which the constructor is called to initialize the instance; the return value type of the constructor itself is void, not "the constructor returns the newly created Object reference", but the value of the new expression is a reference to the newly created object. 2. Purpose: Create an object of a new class. 3. Working mechanism: Allocate memory space for object members, and specify default values. Explicitly initialize member variables, perform construction method calculations, and return reference values. 4. Instance new operation often means opening up new memory in the memory. The memory space is allocated in the heap area in the memory. It is controlled by jvm and automatically manages the memory. Here we use the String class as an example. Pu

How to create and initialize classes and objects in Go language How to create and initialize classes and objects in Go language Jul 21, 2023 pm 07:00 PM

How to create and initialize classes and objects in Go language. Although Go language does not have the concept of classes in traditional object-oriented languages, we can achieve similar functions through structures and methods. In this article, we will learn how to create and initialize classes and objects in Go language. 1. Define the structure of the class In the Go language, we can use the structure to define the attributes and methods of the class. A structure is a custom composite type that can contain multiple fields of different types. For example, if we want to implement a rectangle class, we can define it as

How does the new operator work in js? How does the new operator work in js? Feb 19, 2024 am 11:17 AM

How does the new operator in js work? Specific code examples are needed. The new operator in js is a keyword used to create objects. Its function is to create a new instance object based on the specified constructor and return a reference to the object. When using the new operator, the following steps are actually performed: create a new empty object; point the prototype of the empty object to the prototype object of the constructor; assign the scope of the constructor to the new object (so this points to new object); execute the code in the constructor and give the new object

What is the difference between make and new in go language What is the difference between make and new in go language Jan 09, 2023 am 11:44 AM

Differences: 1. Make can only be used to allocate and initialize data of types slice, map, and chan; while new can allocate any type of data. 2. New allocation returns a pointer, which is the type "*Type"; while make returns a reference, which is Type. 3. The space allocated by new will be cleared; after make allocates the space, it will be initialized.

New Fujifilm fixed-lens GFX camera to debut new medium format sensor, could kick off all-new series New Fujifilm fixed-lens GFX camera to debut new medium format sensor, could kick off all-new series Sep 27, 2024 am 06:03 AM

Fujifilm has seen a lot of success in recent years, largely due to its film simulations and the popularity of its compact rangefinger-style cameras on social media. However, it doesn't seem to be resting on its laurels, according to Fujirumors. The u

See all articles