Custom class writing and invocation examples in JavaScript

Source: Internet
Author: User
Tags instance method visibility

There are already some standard classes in JavaScript, such as date, Array, RegExp, String, Math, number, and so on, which provides a lot of convenience for us to program. But for complex client programs, these are far from enough.

Unlike Java, JAVA2 provides us with a lot of standard classes that basically meet our programming needs, but JavaScript provides few standard classes, and many programming requirements need to be implemented by ourselves, such as JavaScript without Hassi Hashtable, This makes it inconvenient to process key values.

Therefore, I personally think that a complete JavaScript object view should read as follows:

Second, the basic concept

1, customize the object.

According to the JS object extension mechanism, users can customize the JS object, which is similar to the Java language.
Corresponding to the custom object is the JS standard object, such as date, Array, math, and so on.

2, prototype (prototype)

In JS, this is a way to create object properties and methods, and you can add new properties and methods to the object by prototype.
By prototype we can add new properties and methods for the JS standard object, for example, for string objects, we can add a new method trim ().
Unlike a strict programming language (such as Java), we can dynamically add new properties to the JS object during runtime.

Third, grammar rules

1, how objects are created

1) Object Initializer method

Format:

ObjectName = {property1:value1, property2:value2,..., Propertyn:valuen}
property is an object's properties
Value is the values of the object, which can be a string, a number, or one of the three objects

For example:

The code is as follows Copy Code

var user={name: "User1", age:18};
var user={name: "User1", Job:{salary:3000,title:programmer}
In this way, you can also initialize the object's methods, for example:

var user={name: "User1", Age:18,getname:function () {
return this.name;
}
}

The following will be explained in terms of the constructor, including the definition of attributes and methods, and so on.

2 Constructor method

Write a constructor and create the object in a new way, which can have constructor parameters

For example:

The code is as follows Copy Code
function User (name,age) {
This.name=name;
This.age=age;
This.canfly=false;
}
var use=new User ();

2, defining object properties

1 JS can be defined for the object of three types of properties: Private properties, instance properties and class properties, similar to Java, private properties can only be used within the object, the instance properties must be referenced through an instance of the object, and class properties can be referenced directly through the class name.

2 private Property Definition

Private properties can only be defined and used within the constructor.
Syntax format: var propertyname=value;

For example:

The code is as follows Copy Code
function User (age) {
This.age=age;
var IsChild = Age < 12;
This.islittlechild=ischild;
}
var user=new user (15);
alert (user.islittlechild);//The Right way
Alert (user.ischild)//Error: Object does not support this property or method

3 There are two ways to define an instance property:

Prototype way, syntax format: functionname.prototype.propertyname=value
This way, syntax format: this.propertyname=value, note the position used in the example below
The value above can be character Fu Yi, numbers, and objects.

For example:

The code is as follows Copy Code
function User () {}
User.prototype.name= "User1";
user.prototype.age=18;
var user=new user ();
alert (user.age);
—————————————–
function User (name,age,job) {
This.name= "User1";
this.age=18;
This.job=job;
}
alert (user.age);

3 class Attribute definition

Syntax format: functionname.propertyname=value

For example:

The code is as follows Copy Code
function User () {}
user.max_age=200;
user.min_age=0;
alert (user.max_age);

Refer to the class attributes of the JS standard object:

Number.MAX_VALUE//MAX value Math.PI//PI

4 for the definition of attributes, in addition to the above more formal way, there is a very special way to define the syntax format:

Obj[index]=value

Example:

The code is as follows Copy Code
function User (name) {
This.name=name;
this.age=18;
This[1]= "OK";
this[200]= "Year";
}
var user=new user ("User1");
Alert (user[1]);

In the above example, note: Different through this[1] to get the age property, nor through This[0] to get the Name property, that is, the index defined by the index method must be referenced, but not defined by the index, must be referenced in the normal way

3, define object methods

1 JS can define three kinds of methods for objects: Private method, instance method and class method, similar to Java:

Private methods can only be used inside objects
An instance method must be instantiated before the object can be used
Class methods can be used directly by the class name.
Note: The definition of the method cannot be done by the index described above.

2) Defining Private methods

Private methods must be defined within the constructor body and can only be used in the constructor body.

Syntax format:

Function methodname (arg1,..., argn) {}

For example:

The code is as follows Copy Code
function User (name) {
This.name=name;
function Getnamelength (NAMESTR) {
return namestr.length;
}
This.namelength=getnamelength (this.name);
}

3 to define an instance method, there are two ways to do this:

Prototype method, used outside the constructor, syntax format:

The code is as follows Copy Code

Functionname.prototype.methodname=method;
Or

Functionname.prototype.methodname=function (arg1,..., argn) {};
This method, used inside the constructor, syntax format:

This.methodname=method;
Or

This.methodname=function (arg1,..., argn) {};

In the syntax described above, method is an external already existing approach, MethodName the method of the object to be defined, meaning assigning a method directly to an object.
Defining object methods in the manner of function (Arg1,..., argn) {} is what developers should be able to master.

Some examples of defining instance methods: Example 1

The code is as follows Copy Code
function User (name) {
This.name=name;
This.getname=getusername;
This.setname=setusername;
}
function GetUserName () {
return this.name;
}
Function Setusername (name) {
This.name=name;
}

Some examples of defining instance methods: Example 2

The code is as follows Copy Code

function User (name) {
This.name=name;
This.getname=function () {
return this.name;
};
This.setname=function (newName) {
This.name=newname;
};
}

Some examples of defining instance methods: Example 3

The code is as follows Copy Code
function User (name) {
This.name=name;
}
User.prototype.getname=getusername;
User.prototype.setname=setusername ();
function GetUserName () {
return this.name;
}
Function Setusername (name) {
This.name=name;
}

Some examples of defining instance methods: Example 4

The code is as follows Copy Code
function User (name) {
This.name=name;
}
User.prototype.getname=function () {
return this.name;
};
User.prototype.setname=function (newName) {
This.name=newname;
};

4) Defining class methods

A class method needs to be defined outside the constructor, and can be referenced directly by the constructor function name.

Syntax format:

The code is as follows Copy Code

Functionname.methodname=method;

Or

Functionname.methodname=function (arg1,..., argn) {};

Example:

The code is as follows Copy Code

function User (name) {
This.name=name;
}
User.getmaxage=getusermaxage;
function Getusermaxage () {
return 200;
}
Or


User.getmaxage=function () {return 200;};
Alert (User.getmaxage ());

4, a reference to the property and method

1) from the visibility of the said:

Private properties and methods that can only be referenced inside an object.
Instance properties and methods, which can be used anywhere, but must be referenced through objects.
Class properties and methods, which can be used anywhere, but cannot be referenced through instances of objects (this is different from Java, where static members can be accessed through instances).

2 from the object level said:

Like a reference to a Java bean, you can make a deep reference.

Several ways:

Simple properties: Obj.propertyname
Object properties: Obj.innerObj.propertyName
Indexed properties: Obj.propertyname[index]
A deeper reference is similar to the above.

3) from the definition of the way said:

Properties defined by the index method must be referenced by index.
Properties that are defined by a non-index method must be referenced in a normal way.
Note also that the object's methods cannot be defined by the index method.

5. Dynamic additions and deletions of properties and methods

1 for an object that has already been instantiated, we can dynamically add and remove its properties and methods, as follows (assuming that the object instance is obj):
Dynamically increasing object properties

The code is as follows Copy Code

Obj.newpropertyname=value;
Dynamically adding Object methods


Obj.newmethodname=method or =function (arg1,..., argn) {}
To delete an object property dynamically

Delete Obj.propertyname
Dynamic Delete Object method

Delete Obj.methodname

2) Examples:

The code is as follows Copy Code

function User (name) {
This.name=name;
this.age=18;
}
var user=new user ("User1");
User.sister= "Susan";
alert (user.sister);//Run through
Delete User.sister;
alert (user.sister);//Error: Object does not support this property

User.getmothername=function () {return "Mary";}
Alert (User.getmothername ());//Run through
Delete User.getmothername;
Alert (User.getmothername ());//Error: Object does not support this method


Four, summary

1, the custom object mechanism, is one of JS most attractive mechanism, for C + + and Java programmers, this is really great!

2, object creation exists in two ways: object initializers and constructors.

3, Object properties and methods, constraints with visibility, properties and methods with different visibility, and are defined differently.

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.