search
HomeWeb Front-endJS Tutorialjavascript constructor method to define objects

javascript constructor method to define objects

May 04, 2018 pm 04:51 PM
javascriptjsdefinition

This article mainly introduces the JavaScript constructor method to define objects. Friends who need it can refer to it

Javascript is a dynamic language. You can add attributes to the object at runtime and delete the object (delete). Attribute

Copy code The code is as follows:

<html> 
<head>
<script type="text/javascript">
/*
//01.定义对象第一种方式
var object =new Object();
alert(object.username);
//01.1增加属性username
object["username"]="liujianglong";
//object.username="liujl";
alert(object.username);
//01.2删除属性username
delete object.username;//username属性已经从object对象中删除
alert(object.username);
*/
//02.定义对象第二种方式--在javascript中定义对象的一种最常见的方式
var object={name:"zhangsan",age:10,sex:"fale"};
alert(object.name);
alert(object.age);
alert(object.sex);
</script>
</head>         
<body>
</body>
</html>

Attribute name: method name is also ok. Because the function itself is an object

javascript array sorting

Copy code The code is as follows:

<!DOCTYPE html>
<html> 
<head>
<script type="text/javascript">
var array=[1,3,25];
/////////////////////////////////
var compare=function(num1,num2){
    var temp1=parseInt(num1);
    var temp2=parseInt(num2);
    if(temp1<temp2){
        return -1;
    }else if(temp1==temp2){
        return 0;
    }else{
        return 1;
    }
}
//array.sort(compare);//01.函数名是对象引用
////////////////////////////////
//02.匿名函数方式//////////////////
array.sort(function c(num1,num2){
var temp1=parseInt(num1);
    var temp2=parseInt(num2);
    if(temp1<temp2){
        return -1;
    }else if(temp1==temp2){
        return 0;
    }else{
        return 1;
    }
});
/////////////////////////////////
alert(array);
</script>
</head>         
<body>
</body>
</html>

Several ways to define objects in javascript (there is no concept of classes in javascript, only objects)

First One way: Expand its properties and methods based on existing objects

Copy code The code is as follows:

<script type="text/javascript">
//01.基于已有对象扩充其属性和方法
var object=new Object();
object.username="zhangsan";
object.sayName=function (name){
    this.username=name;
    alert(this.username);
}
alert(object.username);
object.sayName("lisi");
alert(object.username);
</script>

This method has limitations, because javascript does not have the same features as java The concept of class, write a class, and then new can get an object with these attributes and methods.

If you want to own object2 at this time, you can only write another copy of the code above, which is not good.

Second method: Factory method

Similar to the static factory method in java.

Copy code The code is as follows:

<!DOCTYPE html>
<html> 
<head>
<script type="text/javascript">
//对象工厂方法
var  createObject=function(){
    var object=new Object();
    object.username="zhangsan";
    object.password="123";
    object.get=function(){
        alert(this.username+" , "+object.password); 
    }
    return object;
}
var obj1=createObject();
var obj2=createObject();
obj1.get();
//修改对象2的密码
obj2["password"]="123456";
obj2.get();
</script>
</head>         
<body>
</body>
</html>

There are disadvantages in creating objects in the above way (each object has a get method, thus wasting memory), after improvement Factory mode (all objects share a get method):

Copy code The code is as follows:

<!DOCTYPE html>
<html> 
<head>
<script type="text/javascript">
//所有对象共享的get方法
var get=function(){
    alert(this.username+" , "+this.password);
}
//对象工厂方法
var createObject=function(username,password){
    var object=new Object();
    object.username=username;
    object.password=password;
    object.get=get;//注意:这里不写方法的括号
    return object;
}
//通过工厂方法创建对象
var object1=createObject("zhangsan","123");
var object2=createObject("lisi","345");
//调用get方法
object1.get();
object2.get();
</script>
</head>         
<body>
</body>
</html>

The third way: Define the object in constructor mode

Copy code The code is as follows:

<!DOCTYPE html>
<html> 
<head>
<script type="text/javascript">
var get=function(){
    alert(this.username+" , "+this.password);
}
function Person(username,password){
    //在执行第一行代码前,js引擎会为我们生成一个对象
    this.username=username;
    this.password=password;
    this.get=get;
    //在此处,有一个隐藏的return语句,用于返回之前生成的对象[这点是和工厂模式不一样的地方]
}
var person=new Person("zhangsan","123");
person.get();
</script>
</head>         
<body>
</body>
</html>

Fourth way: Prototype method to create objects

Prototype is an attribute in the object object, and all person objects are also You can have the prototype attribute.

You can add some attributes and methods to the prototype of the object.

Disadvantages of simply using the prototype method to create objects: ① Parameters cannot be passed, and its value can only be changed after the object is created.

Copy code

The code is as follows:

<!DOCTYPE html>
<html> 
<head>
<script type="text/javascript">
function Person(){
}
Person.prototype.username="zhangsan";
Person.prototype.password="123";
Person.prototype.getInfo=function(){
    alert(this.username+" , "+this.password);
}
var person1=new Person();
var person2=new Person();
person1.username="lisi";
person1.getInfo();
person2.getInfo();
</script>
</head>         
<body>
</body>
</html>

Copy code The code is as follows:

<!DOCTYPE html>
<html> 
<head>
<script type="text/javascript">
function Person(){
}
Person.prototype.username=new Array();
Person.prototype.password="123";
Person.prototype.getInfo=function(){
    alert(this.username+" , "+this.password);
}
var person1=new Person();
var person2=new Person();
person1.username.push("wanglaowu");
person1.username.push("wanglaowu2");
person2.password="456";
person1.getInfo    ();
person2.getInfo();
</script>
</head>         
<body>
</body>
</html>

Simply using the prototype method to define an object cannot assign attributes to the constructor The initial value can only be changed after the object is generated. The fifth way: use the prototype constructor method to define the object----it is recommended to use

The properties between the objects do not interfere with each other

The same method is shared between each object

Copy code
The code is as follows:

<!DOCTYPE html>
<html> 
<head>
<script type="text/javascript">
//使用原型+构造函数方式来定义对象
function Person(){
    //属性 定义在构造函数中
    this.username=new Array();
    this.password="123";
}
    //方法 定义在原型中
Person.prototype.getInfo=function(){
    alert(this.username+" , "+this.password);
}
var p1=new Person();
var p2=new Person();
p1.username.push("zhangsan");
p2.username.push("lisi");
p1.getInfo();
p2.getInfo();
</script>
</head>         
<body>
</body>
</html>

The sixth way: dynamic prototype method----it is recommended to use Pass the flag in the constructor Quantity allows all objects to share a method, and each object has its own properties.

Copy code

The code is as follows:

<!DOCTYPE html>
<html> 
<head>
<script type="text/javascript">
var Person=function (username,password){
    this.username=username;
    this.password=password;
    if(typeof Person.flag=="undefined"){
        alert("invoked");
        Person.prototype.getInfo=function(){
            alert(this.username+" , "+this.password);
        }
        Person.flag=true;    
    }
}
var p1=new Person("zhangsan","123");
var p2=new Person("lisi","456");
p1.getInfo();
p2.getInfo();
</script>
</head>         
<body>
</body>
</html>

Related recommendations:

Javascript constructor, public, private privileges and static member definition methods_ javascript skills

The above is the detailed content of javascript constructor method to define objects. 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

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools