JavaScript Create Class

Source: Internet
Author: User

It is relatively simple to define and use objects in JavaScript, and you can define and initialize an object using {}.

This definition of the object is an instance of the object class, which can dynamically add properties and methods during execution, which is very flexible. Let's look at an example:

var obj = {property: "This is a parameter", Method:function () {return "This is a function, method is the function name";}};

This defines an instance of the object class. There is a parameter and a method, the property and methods are defined parameter names and function names, respectively.

See below how to use this object

Window.onload=function () {obj.tmp = "This is a property added during the run"; Alert ("Method:" +obj.method () + "parameter:" +obj.property+ "temporarily added:" + OBJ.TMP);};

The window pops up when the page loads


However, this creation implies a risk of not being able to detect bugs directly.

So JavaScript also supports custom classes.

All instances created by custom classes will have the same properties and methods. However, this method cannot dynamically add properties and methods.

Here's how to create a class method in a custom way:

First define the specific structure of this class:

function Rectangle (width,height) {this.width = Width;this.height = Height;this.area = function () {return this.width* This.height;};};

Functions are also an object in JavaScript, but you must use the () operator when calling a function, and look at the resulting object

Window.onload=function () {var re = new Rectangle (3, 4), alert ("width:" +re.width+ "High:" +re.height+ "area:" +re.area ())};
This pops up the form after the page opens:


JavaScript Create Class

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.