Home Web Front-end JS Tutorial Javascript uses function to define constructors_javascript tips

Javascript uses function to define constructors_javascript tips

May 16, 2016 pm 06:33 PM
function Constructor

The syntax for creating objects in Javascript is the new operator followed by a function call. For example,

Copy code The code is as follows:

var obj = new Object();
var date = new Date();

Operator new first creates a new object without any attributes, and then calls the function, passing the new object as the value of the this keyword.
Copy code The code is as follows:

Pseudocode implementation of var date = new Date() That is
var obj = {};
var date = Date.call(obj);

The function of the constructor is to initialize a newly created object and set it before using the object properties of the object. If you define your own constructor, you only need to write a function that adds attributes to this. The following code defines a constructor:
Copy code The code is as follows:

function Rectangle( w, h)
{
this.width = w;
this.height = h;
}

Then, you can use the new operator to call this function Create an instance of the object
Copy the code The code is as follows:

var rect = new Rectange(4, 8);

Constructor return value
Constructors in Javascript usually have no return value. However, functions are allowed to return values. If a constructor has a return value, the returned object becomes the value of the new expression. In this case, the object used as this will be discarded.

Use constructor definition method
Syntax
Copy code The code is as follows:

var object=new objectname();
var -- declare object variable
object -- the name of the object
new -- new keyword (JavaScript keyword)
objectname -- Constructor name

Example
Copy code The code is as follows:

//Define constructor
function Site(url, name)
{
this.url = "www.jb51.net";
this.name ="Dream City";
}
//Use the constructor to generate an instance of a JavaScript object
var mysite = new Site();
alert(mysite.url);

The constructor can usually Initialize some contents in the object. Some objects provided within JavaScript usually need to be generated using the constructor method. The content of JavaScript functions will be introduced in the next chapter.

Create JavaScript objects by direct definition
Copy code The code is as follows:

//Define object syntax
var object={};
//Attribute syntax within the object (property name (property) and attribute value (value) appear in pairs)
object.property=value ;
//Function syntax within the object (function name (func) and function content appear in pairs)
object.func=function(){...;};

var -- declare object variable
object -- the name of the object
property -- the property name of the object
func -- the method name of the object
Description: Objects can contain some properties (functions can Seen as special properties with parentheses), each property has a name and a value. The name can be any string or even empty. The value can be any JavaScript type, but cannot be undefined.

Example of object defined using definition method
Copy code The code is as follows:

var site = {};
site.URL = "www.jb51.net";
site.name = "Script Home";
site.englishname = "jb51";
site .author = "Script";
site.summary = "Free Web Design Tutorial";
site.pagescount = 100;
site.isOK = true;
site.startdate = new Date( 2005, 12);
site.say = function(){alert(this.englishname " say : hello world!")};
site.age = function(){var theage=(new Date() .getFullYear())-site.startdate.getFullYear();alert(this.name "already" theage "year old!")}

Example of using a constructor to create a JavaScript object--you can try editing
Using a constructor to create a JavaScript object
The above method defines a site object and defines seven properties for it, as well as two personal properties. method.

The say method will print out the string of jb51 say: hello world!
The age method will calculate the age of the Dream City website
Monkey Tip: Note that each attribute and function must be preceded by The name of the object, otherwise JavaScript cannot determine which object it belongs to.

The following course will explain the extension of the direct definition method, the JSON definition method.
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)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months 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)

What does function mean? What does function mean? Aug 04, 2023 am 10:33 AM

Function means function. It is a reusable code block with specific functions. It is one of the basic components of a program. It can accept input parameters, perform specific operations, and return results. Its purpose is to encapsulate a reusable block of code. code to improve code reusability and maintainability.

What is the purpose of the 'enumerate()' function in Python? What is the purpose of the 'enumerate()' function in Python? Sep 01, 2023 am 11:29 AM

In this article, we will learn about enumerate() function and the purpose of “enumerate()” function in Python. What is the enumerate() function? Python's enumerate() function accepts a data collection as a parameter and returns an enumeration object. Enumeration objects are returned as key-value pairs. The key is the index corresponding to each item, and the value is the items. Syntax enumerate(iterable,start) Parameters iterable - The passed in data collection can be returned as an enumeration object, called iterablestart - As the name suggests, the starting index of the enumeration object is defined by start. if we ignore

Detailed explanation of the role and function of the MySQL.proc table Detailed explanation of the role and function of the MySQL.proc table Mar 16, 2024 am 09:03 AM

Detailed explanation of the role and function of the MySQL.proc table. MySQL is a popular relational database management system. When developers use MySQL, they often involve the creation and management of stored procedures (StoredProcedure). The MySQL.proc table is a very important system table. It stores information related to all stored procedures in the database, including the name, definition, parameters, etc. of the stored procedures. In this article, we will explain in detail the role and functionality of the MySQL.proc table

Constructor in Python Constructor in Python Sep 02, 2023 pm 04:29 PM

In Python, every class has a constructor, which is a special method specified inside the class. The constructor/initializer will be called automatically when a new object is created for the class. When an object is initialized, the constructor assigns values ​​to data members in the class. There is no need to define the constructor explicitly. But in order to create a constructor, we need to follow the following rules - For a class, it is allowed to have only one constructor. The constructor name must be __init__. Constructors must be defined using instance properties (just specify the self keyword as the first argument). It cannot return any value except None. Syntax classA():def__init__(self):pass Example Consider the following example and

The usage and function of Vue.use function The usage and function of Vue.use function Jul 24, 2023 pm 06:09 PM

Usage and Function of Vue.use Function Vue is a popular front-end framework that provides many useful features and functions. One of them is the Vue.use function, which allows us to use plugins in Vue applications. This article will introduce the usage and function of the Vue.use function and provide some code examples. The basic usage of the Vue.use function is very simple, just call it before Vue is instantiated, passing in the plugin you want to use as a parameter. Here is a simple example: //Introduce and use the plug-in

What is the usage of js function What is the usage of js function Oct 07, 2023 am 11:25 AM

The usage of js function function is: 1. Declare function; 2. Call function; 3. Function parameters; 4. Function return value; 5. Anonymous function; 6. Function as parameter; 7. Function scope; 8. Recursive function.

C++ syntax error: The constructor defined outside the class must be added with the class name as a qualifier. How should it be corrected? C++ syntax error: The constructor defined outside the class must be added with the class name as a qualifier. How should it be corrected? Aug 22, 2023 pm 02:00 PM

C++ is a widely used object-oriented programming language. When defining the constructor of a class in C++, if you want to place the definition of the constructor outside the class, you need to add the class name as a qualifier to the definition of the constructor. To specify which class this constructor belongs to. This is a basic rule of C++ syntax. If this rule is not followed when defining the constructor of a class, a compilation error will appear, prompting "Constructors defined outside the class must be qualified with the class name." So, if you encounter this kind of compilation error, you should

file_exists() function in PHP file_exists() function in PHP Sep 14, 2023 am 08:29 AM

The file_exists method checks whether a file or directory exists. It accepts as argument the path of the file or directory to be checked. Here's what it's used for - it's useful when you need to know if a file exists before processing it. This way, when creating a new file, you can use this function to know if the file already exists. Syntax file_exists($file_path) Parameters file_path - Set the path of the file or directory to be checked for existence. Required. Return file_exists() method returns. Returns TrueFalse if the file or directory exists, if the file or directory does not exist Example let us see a check for "candidate.txt" file and even if the file

See all articles