Home > Web Front-end > JS Tutorial > Detailed explanation of custom constructor based on JavaScript_Basic knowledge

Detailed explanation of custom constructor based on JavaScript_Basic knowledge

WBOY
Release: 2016-05-16 17:35:31
Original
990 people have browsed it

Javascript does not support real classes like Java, C# and other languages. But pseudo classes can be defined in js. The tools for doing this are constructors and prototype objects. First introduce the constructor in js.

The syntax for creating objects in Javascript is to follow 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, then calls the function, passing the new object as the value of the this keyword .
The pseudo code implementation of var date = new Date() is

var obj = {};

var date = Date.call(obj);

The function of the constructor is to initialize a newly created object and set the properties of the object before using it. 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 an object

var rect = new Rectange(4,8);

The return value of the constructor

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.

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template