Based on JS object, Operation Properties, methods

Source: Internet
Author: User
Tags instance method

One, overview

In the Java language, we can define our own classes and create objects from them, and in JavaScript we can also define our own classes, such as defining the user class, the Hashtable class, and so on.

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 our programming. 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 offers very few standard classes, and many programming requirements need to be implemented ourselves, such as JavaScript without Hassi Hashtable, In this case, it is inconvenient to handle the key value.

Therefore, I personally think that a complete view of JavaScript objects should look like this:

Second, the basic concept

1, custom 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 through prototype.

By prototype we can add new properties and methods to the JS standard object, for example, for a string object, we can add a new method trim () to it.

Unlike strict programming languages such as Java, we can dynamically add new properties to the JS object during runtime.

Third, grammatical rules

1, how objects are created

1) object initializer mode

Format: ObjectName = {property1:value1, property2:value2,..., Propertyn:valuen}

property is an attribute of an object

Value is the value of the object, which can be one of three strings, numbers, or objects

For example: Var user={name: "User1", age:18};

var user={name: "User1", Job:{salary:3000,title:programmer}

You can also initialize the method of an object in this way, for example:

?
1234567 varuser={name:“user1”,age:18,getName:function(){  return this.name; } }

The following will be the focus of the constructor, including the definition of properties and methods, etc., as well as the way the constructor is explained.

2) constructor function mode

Write a constructor and create the object by using the new method, which can have the constructor parameters

For example:

?
1234567891011 functionUser(name,age){  this.name=name;  this.age=age;  this.canFly=false; }  var use=newUser();

2, defining object properties

1) JS can define three types of properties for an object: Private properties, instance properties, and class properties, like Java, where private properties can only be used inside objects, instance properties must be referenced through an instance of an object, and class properties can be referenced directly through the class name.

2) Private Property definition

Private properties can be defined and used only within the constructor.

Syntax format: var propertyname=value;

For example:

?
123456789101112131415 functionUser(age){  this.age=age;  var isChild=age<12;  this.isLittleChild=isChild; }  var user=new User(15);  alert(user.isLittleChild);//正确的方式 alert(user.isChild);//报错:对象不支持此属性或方法

3) instance attribute definitions, there are two ways:

Prototype way, syntax format: functionname.prototype.propertyname=value

This way, syntax format: this.propertyname=value, note the position used in the following example

The above value can be a character a, a number, and an object.

For example:

?
1234567891011121314151617181920212223 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:

?
1234567 functionUser(){ }  User.MAX_AGE=200;  User.MIN_AGE=0; alert(User.MAX_AGE);

Refer to the class properties of the JS standard object:

Number.MAX_VALUE//Maximum value Math.PI//PI

4) for the definition of attributes, in addition to the more formal way above, there is a very special way of defining, syntax format: obj[index]=value

Example:

?
123456789101112131415 functionUser(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 defined by the index method must use the index way to refer to, but not by the index method, must be referenced in the normal way

3, defining Object methods

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

Private methods can only be used inside an object

The instance method must be instantiated before the object can be used

Class methods can be used directly from the class name.

Note: The definition of a method cannot be done by means of the index described above.

2) Define private methods

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

Syntax format: function methodName (arg1,..., argN) {}

For example:

?
12345678910111213 functionUser(name){  this.name=name; function getNameLength(nameStr){  return nameStr.length;  }  this.nameLength=getNameLength(this.name); }

3) Define an instance method, which can now be used in two ways:

Prototype mode, used outside of the constructor, in syntax format:

Functionname.prototype.methodname=method;

Or

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

This method, used inside the constructor, is syntactically formatted:

This.methodname=method;

Or

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

In the syntax described above, method is a method that already exists outside, MethodName the object to be defined by means of a method that assigns an external method directly to the object.

Defining an object method in the same way as function (Arg1,..., ArgN) {} Is what developers should know.

Some examples of defining instance methods: Example 1

?
123456789101112131415161718192021 functionUser(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

?
1234567891011121314151617 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

?
12345678910111213141516171819202 1 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

?
1234567891011121314151617 functionUser(name){  this.name=name;  }  User.prototype.getName=function(){  return this.name;  };  User.prototype.setName=function(newName){ this.name=newName; };

4) Defining class methods

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

Syntax format:

Functionname.methodname=method;

Or

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

Example:

?
12345678910111213 functionUser(name){  this.name=name; }  User.getMaxAge=getUserMaxAge;  function getUserMaxAge(){  return 200; }

Or

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

Alert (User.getmaxage ());

4, references to properties and methods

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 by an object.

Class properties and methods can be used anywhere, but not by an instance of an object (this differs from Java in that static members in Java can be accessed through an instance).

2) from the object level, say:

Similar to a reference to a Java bean, a deep reference can be made.

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 that are defined by the index method must be referenced by index.

Properties that are defined by non-index methods must be referenced in a normal way.

Also note: Object methods cannot be defined by index.

5. Dynamic addition and deletion of attributes and methods

1) For an object that has already been instantiated, we can dynamically add and remove its properties and methods, with the following syntax (assuming the object instance is obj):

Dynamically increase object Properties

Obj.newpropertyname=value;

Dynamically increasing object methods

Obj.newmethodname=method or =function (arg1,..., argN) {}

Dynamically deleting object properties

Delete Obj.propertyname

Dynamic Delete Object Methods

Delete Obj.methodname

2) Example:

?
12345678910111213141516171819202122232425 function User(name){ this.name=name; this.age=18; } var user=new User(“user1”); user.sister=“susan”; alert(user.sister);//运行通过 delete user.sister; alert(user.sister);//报错:对象不支持该属性 user.getMotherName=function(){return “mary”;} alert(user.getMotherName());//运行通过 delete user.getMotherName; alert(user.getMotherName());//报错:对象不支持该方法

Four, summary

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

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

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

Based on JS object, Operation Properties, methods

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.