Home Web Front-end JS Tutorial javascript constructor method to define objects

javascript constructor method to define objects

May 04, 2018 pm 04:51 PM
javascript js definition

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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 after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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 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

Video Face Swap

Video Face Swap

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

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)

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

The definition and function of MySQL composite primary key The definition and function of MySQL composite primary key Mar 15, 2024 pm 05:18 PM

The composite primary key in MySQL refers to the primary key composed of multiple fields in the table, which is used to uniquely identify each record. Unlike a single primary key, a composite primary key is formed by combining the values ​​of multiple fields. When creating a table, you can define a composite primary key by specifying multiple fields as primary keys. In order to demonstrate the definition and function of composite primary keys, we first create a table named users, which contains three fields: id, username and email, where id is an auto-incrementing primary key and user

What is Discuz? Definition and function introduction of Discuz What is Discuz? Definition and function introduction of Discuz Mar 03, 2024 am 10:33 AM

"Exploring Discuz: Definition, Functions and Code Examples" With the rapid development of the Internet, community forums have become an important platform for people to obtain information and exchange opinions. Among the many community forum systems, Discuz, as a well-known open source forum software in China, is favored by the majority of website developers and administrators. So, what is Discuz? What functions does it have, and how can it help our website? This article will introduce Discuz in detail and attach specific code examples to help readers learn more about it.

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Introduction to PHP interfaces and how to define them Introduction to PHP interfaces and how to define them Mar 23, 2024 am 09:00 AM

Introduction to PHP interface and how it is defined. PHP is an open source scripting language widely used in Web development. It is flexible, simple, and powerful. In PHP, an interface is a tool that defines common methods between multiple classes, achieving polymorphism and making code more flexible and reusable. This article will introduce the concept of PHP interfaces and how to define them, and provide specific code examples to demonstrate their usage. 1. PHP interface concept Interface plays an important role in object-oriented programming, defining the class application

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

The definition and use of full-width characters The definition and use of full-width characters Mar 25, 2024 pm 03:33 PM

What are full-width characters? In computer encoding systems, double-width characters are a character encoding method that takes up two standard character positions. Correspondingly, the character encoding method that occupies a standard character position is called a half-width character. Full-width characters are usually used for input, display and printing of Chinese, Japanese, Korean and other Asian characters. In Chinese input methods and text editing, the usage scenarios of full-width characters and half-width characters are different. Use of full-width characters Chinese input method: In the Chinese input method, full-width characters are usually used to input Chinese characters, such as Chinese characters, symbols, etc.

See all articles