1) how to create an object:
1. Use constructor, for example:
Var obj = new Object () // var can be omitted
Var obj = new Date ()
2. Use object literals ),For example:
Program code
Var obj = "123" // create a String object
Var obj =/^ abc $ // create a RegExp object
In a more complex scenario, we can directly generate a custom property-only object:
Program code
Var obj = {
Name: "killercat ",
Home: "www.i170.com/user/killercat"
}
Document. write (obj. name + "<br/> ")
Document. write (obj. home)
Result:
Killercat
Www.i170.com/user/killercat
2) attributes in JavaScript:
Str = "www.i170.com/user/killercat" // reference of a string object
Document. write (str. length)
You can access the property by adding "." To the object and the property name. You can also modify the property or even add an attribute, for example:
Var obj = new Object ()
Obj. name = "killercat" // directly add an attribute to the object
Document. write (obj. name) // Access Object Attributes
Obj. name = "kcat" // Modify Object Attributes
Document. write (obj. name)
Enumerated property values:
You can use the for... in statement to enumerate attributes (specifically, the enumeration attribute name ).
For (ele in window ){
Document. write (ele + "<br/> ")
}
How to get the attribute value?
Obj = new Object ()
Obj. p1 = ""
Obj. p2 = "B"
Obj. p3 = "c"
For (ele in obj)
Document. write (obj. ele) // This is a possible mistake for beginners. The obj. ele value is undefined.
The access property value should be as follows:
Document. write (eval ("obj." + ele ))
Undefined attributes:
Obj = new Object ()
Document. write (obj. name)
The result is undefined.
Delete attributes:
Obj = new Object ()
Obj. name = "killercat"
Delete obj. name
Document. write (obj. name)
The result is undefined.
Understanding attributes:
In Java and c ++, attributes either belong to a class (Class Attribute or static attribute) or an object, that is, an object of the same class, there must be the same attributes, but JavaScript is different. Objects can have different attributes. In addition to such attributes, JavaScript also has static attributes (variables ).
3) Constructor
For some unknown reasons, some people seem unwilling to mention classes in JavaScript, instead of "object types", or even some people call functions directly, as a result, we can see the following statement: "An object is generated by pre-defined functions ". This document uses the class.
The method for defining JavaScript methods is the same as that for defining classes:
Function User (name, sex) {// defines the class User
This. name = name;
This. sex = sex;
}
User = new User ("kc", "man ")
Document. write (user. name + "<br/>" + user. sex)
Contructor is used to initialize attributes (variables)