


Summary of several methods of creating objects in javascript_javascript skills
Foreword:
With the rise of web 2.0 (the most representative one is Ajax technology), JavaScript is no longer a "toy language" in the eyes of programmers. Programming is constantly being simplified, but the requirements for "user experience, performance, compatibility, scalability..." are constantly improving, and excellent frameworks (class libraries) such as Prototype, jQuery, ExtJs, and Dojo have emerged. , greatly simplifying web development.
More and more people are beginning to study and use javascript in depth. Of course, enterprises have higher and higher requirements for developers. Let’s take my own experience as an example. In the early 2000s, I was able to use JavaScript to write some page UI effects and do website form verification and other operations. I thought it was pretty cool at the time. But now, if you don’t even know what XMLHttpRequest and JSON are, and you don’t even understand object-oriented/object-based programming in JavaScript, do you still dare to call yourself an excellent web programmer? (Friends who pay attention to cutting-edge technology must know node.js and MongoDB, both of which are inseparable from JavaScript.)
The flexibility of JavaScript is something that people both love and hate. It is typically easy to get started but difficult to master. Understanding javascript OOP/object-based programming is the watershed for judging a programmer's javascript level. In JavaScript object-based programming, the most basic thing is "creating objects", which often makes many programmers who are familiar with other language-oriented languages (Java, C#, C) feel confused or difficult to adapt to. Therefore, this article will first introduce to you several common ways to create objects in JavaScript.
1. Creation of simple objects Create an object using object literal {} (the simplest, easy to understand, recommended)
var Cat = {};//JSON
Cat.name="kity"; //Add attributes and assign values
Cat.age=2;
Cat.sayHello=function(){
alert("hello " Cat.name ", this year " Cat["age"] " is old ");//You can use "." to access attributes, or you can use HashMap to access
}
Cat.sayHello();//Call the object's (method) function
2. Use function to simulate class (no-argument constructor)
2.1 Create an object, equivalent to new instance of a class
function Person(){
}
var personOne=new Person();//Define a function. If there is the new keyword to "instantiate", then the function can be regarded as a class
personOne.name="dylan ";
personOne.hobby="coding";
personOne.work=function(){
alert(personOne.name " is coding now...");
}
personOne.work();
2.2 It can be implemented using a parameterized constructor, which makes definition more convenient and more scalable (recommended)
function Pet(name,age,hobby){
this. name=name;//this scope: current object
this.age=age;
this.hobby=hobby;
this.eat=function(){
alert("My name is" this.name ", I like " this.hobby ", and I am also a foodie");
}
}
var maidou =new Pet("McDull",5,"sleeping");//Example Transform/create objects
maidou.eat();//Call the eat method (function)
3. Use factory method to create (Object keyword)
var wcDog =new Object();
wcDog .name="Wangcai";
wcDog.age=3;
wcDog.work=function(){
alert("I am " wcDog.name ", woof woof woof...... ");
}
wcDog.work();
4. How to use prototype objects prototype keyword
function Dog(){
}
Dog.prototype.name=" Wangcai";
Dog.prototype.eat=function(){
alert(this.name "Is a foodie");
}
var wangcai =new Dog();
wangcai .eat();
5. Mixed mode (prototype and constructor)
function Car(name,price){
this.name=name;
this.price=price;
}
Car.prototype. sell=function(){
alert("I am " this.name ", I am selling " this.price "10,000 yuan");
}
var camry =new Car("Camry",27);
camry.sell();
6. Dynamic prototype method (can be regarded as It is a special case of mixed mode)
function Car(name,price){
this.name=name;
this.price=price;
if(typeof Car.sell=="undefined"){
Car.prototype .sell=function(){
alert("I am " this.name ", and I am selling " this.price "10,000 yuan");
}
Car.sell=true;
}
}
var camry =new Car("Camry",27);
camry.sell();
The above are the most commonly used ways to create objects in JavaScript. Beginners may faint or even feel worried after seeing it. In fact, there is no need to worry at all. You only need to master one or two of these methods, and you only need to understand the other ones. This is the flexibility of JavaScript. Each method must have its advantages and disadvantages, so there is no fixed recommendation. Just choose the method that is easiest for you to understand and master. Moreover, everyone's coding style may be different. In the future, you may need to study the source code of jQuery, or refer to other plug-ins to rewrite it, or develop your own plug-in. You will also need to understand other people's coding styles. These class libraries and plug-ins are all based on object-oriented/object-based.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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 use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

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

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).
