DOM note (11): basic understanding and creation of JavaScript objects, domjavascript
1. What is an object?
The Object-Oriented (OO) language has a flag, that is, it has the concept of classes, such as C ++ and Java. However, ECMAScript does not have the concept of classes. The ECMAScript-262 defines an object as a set of unordered properties that can contain basic values, objects, or functions. Generally, objects in ECMAScript are a set of data and functions. They are created using the new operator followed by the name of the object type to be created. Each object is created based on a reference type. The reference can be a native type (reference type) or a developer-defined type.
Ii. Object
Like other OO languages, the Object type is the basis of all its instances. Any attributes and methods of Object types also exist in more specific objects.
// Create the object var o = new Object (); // if no parameter is passed, parentheses can be omitted, but var o = new Object is not recommended;
Each instance of an Object has common basic attributes and methods.
| Attribute or Method |
Description |
| Constructor |
Point to the constructor that creates the current object |
| HasOwnProperty (name) |
Checks whether a given property name exists in an instance object (not a prototype object. Name is specified as a string |
| IsPropertyOf (object) |
Checks whether the input object is the prototype object of the method caller. General Format: Class. prototype. isPropertyOf (object) |
| PropertyIsEnumerable (pr) |
Check whether the property pr can be enumerated cyclically using for-in. Attribute pro is specified as a string |
| ToLocaleString () |
Returns the string representation of an object. Corresponds to the region and Environment |
| ToString () |
String Representation of the returned object |
| ValueOf () |
Returns the string, value, or Boolean representation of an object. |
Iii. Object Property types
ECMAScript 5 defines the internal features used to describe various features of attributes. To implement JavaScript Engine Services, these features cannot be directly accessed in JavaScript. There are two types of attributes: data attributes and accessors attributes.
1. Data attributes
The data attribute contains a data value location where data is read and written. ECMAScript defines four features to describe the behavior of data attributes:
| Features |
Description |
| [[Retriable] |
Whether the attribute can be deleted through delete to redefine the attribute, whether the attribute's characteristics can be modified, and whether the attribute can be changed to the accessors attribute. The default value is true. |
| [[Enumerable] |
Indicates that all attributes can be returned through the for-in loop. The default value is true. |
| [[Writable] |
Indicates whether the attribute can be modified. The default value is true. |
| [[Value] |
Represents the data value of an attribute. The default value is undefined. |
2. accessors
The accessors attribute does not contain data values and cannot be directly defined. When reading the accessors attribute, call the getter function, which returns the valid value. When writing the accessors attribute, call the setter function and input a new value. The accessors also have four attributes:
| Features |
Description |
| [[Retriable] |
Whether the attribute can be deleted through delete to redefine the attribute, whether the attribute's characteristics can be modified, and whether the attribute can be changed to the accessors attribute. The default value is true. |
| [[Enumerable] |
Indicates that all attributes can be returned through the for-in loop. The default value is true. |
| [[Get] |
The function called when reading the attribute. The default value is undefined. |
| [[Set] |
The function called when writing the attribute. The default value is undefined. |
How can I obtain the default features of object attributes?
var person = { name:"dwqs", age:20, interesting:"coding", blog:"www.ido321.com"};var desc = Object.getOwnPropertyDescriptor(person,"age");alert(desc.value); //20alert(desc.configurable); //truealert(desc.enumerable); //truealert(desc.writable); //true
Use the Object. getOwnPropertyDescriptor (object, prop) of ECMAScript 5 to obtain the descriptor of the given attribute. The object is the Object where the attribute is located, and the prop is the string form of the given attribute, returning an object. If prop is an accessors attribute, the returned objects include retriable, enumerable, set, and get. If prop is a data attribute, the returned objects include retriable, enumerable, writable, and value.
Attribute features cannot be directly defined. ECMAScript provides Object. defineProperty (obj, prop, desc): obj is the object where the attribute is located. prop is a string of the given attribute. desc contains the object of the feature set.
Var person = {
Name: "dwqs ",
Age: 20,
Interesting: "coding ",
Blog: "www.ido321.com"
};
// Define the sex property. writable is false, so it cannot be modified.
Object. defineProperty (person, "sex ",{
Writable: false,
Value: "male"
});
Alert (person. sex); // male
// An error occurs in strict mode. Non-strict mode assignment is ignored.
Person. sex = "female"; // writable is false, so it cannot be modified.
Alert (person. sex); // male
You can call Object. defineProperty () multiple times to modify the feature. However, if you define resumable as false, you cannot call the Object. defineProperty () method to change it to true. In addition, if you do not specify the attribute value when calling Object. defineProperty (), the default values of retriable, enumerable, and writable are false.
Var person = {name: "dwqs", age: 20, interesting: "coding", blog: "www.ido321.com"}; Object. defineProperty (person, "sex", {retriable: false, value: "male"}); alert (person. sex); // maledelete person. sex; // The value of retriable is false. An error occurs in strict mode. If not, this operation alert (person. sex); // male // throw the Cannot redefine property: sex error Object. defineProperty (person, "sex", {retriable: true, value: "male"}); alert (person. sex); // The delete person cannot be displayed. sex; alert (person. sex); // No pop-up allowed
You can also use Object. defineProperties (obj, props) to define multiple attributes simultaneously: obj is the Object where the attribute is located, and props is an Object that contains multiple attribute definitions.
Var book = {};
Object. defineProperties (book ,{
_ Year :{
Value: 2014
},
Edition :{
Value: 1
},
Year :{
Get: function ()
{
Returnthis. _ year;
},
Set: function (newValue)
{
If (newValue> 2014)
{
This. _ year = newValue;
This. edition + = newValue-2014
}
}
}
});
Var descs = Object. getOwnPropertyDescriptor (book, "_ year ");
Alert (descs. value); // 2014
// When calling Object. defineProperty (), if the attribute value is not specified, the default values of retriable, enumerable, and writable are false.
Alert (descs. retriable); // false
Alert (typeof descs. get); // undefined
You can specify either get or set. Only get indicates that the attribute is read-only. Only set indicates that the attribute can only be written and cannot be read.
3. Enumeration PropertiesECMAScript 5 defines two common methods for enumeration attributes: Object. keys (obj): lists all the attributes that obj can enumerate. That is, the attribute [[Enumerable] is a property of true. Object. getOwnPropertyNames (obj): lists all the attributes that can be enumerated by obj and cannot be enumerated, regardless of whether [[Enumerable] is true or false.
var person = { name:"dwqs", age:20, interesting:"coding", blog:"www.ido321.com"};Object.defineProperty(person,"sex",{ configurable:false, value:"male"});alert(Object.keys(person)); //name,age,interesting,blogalert(Object.getOwnPropertyNames(person)); //name,age,interesting,blog,sex
Because the sex property is defined using the defineProperty () method, the default value of unspecified enumerable is false. Therefore, the sex attribute is not returned in the first pop-up box, but the second result is returned.
4. Object Creation Method
1. Factory Model
function Person(name,age,blog){ var o = new Object(); o.name = name; o.age = age; o.blog = blog; o.interest = function() { alert("I like coding and writing blog!!!"); } return o;}var per1 = Person("dwqs",20,"www.ido321.com");alert(per1.name); //dwqs
Advantage: saves code and prevents redundancy.
Disadvantage: the object cannot be identified, that is, each instance created has the same attribute and cannot reflect the object type.
2. constructor Mode
function Person(name,age,blog){ this.name = name; this.age = age; this.blog = blog; this.interest = function() { alert("I like coding and writing blog!!!"); }}var per1 = new Person("dwqs",20,"www.ido321.com");alert(per1.name);
Advantage: each instance is created differently and different objects can be identified.
Disadvantage: When an instance is created, all methods of the instance are re-created. The corresponding solution can define the method globally or the prototype object.
function Person(name,age,blog){ this.name = name; this.age = age; this.blog = blog; this.interest = my;} function my(){ alert("I like coding and writing blog!!!");}
In this way, all instances of Person share the my () method.
3. Prototype
function Person(){ }Person.prototype.name = "dwqs";Person.prototype.age = 20;Person.prototype.blog = "www.ido321.com";Person.prototype.interest = function(){ alert("I like coding and writing blog!!!");}var per1 = new Person();alert(per1.name); //dwqsvar per2 = new Person();alert(per1.interest == per2.interest); //true
Per1 and per2 share all the attributes and methods defined on the prototype. Obviously, each instance cannot be independent, not what we want. For more information about the prototype, see the subsequent notes.
4. prototype mode + constructor mode (recommended)
function Person(name,age,blog){ this.name = name; this.age = age; this.blog = blog;}Person.prototype.interest = function(){ alert("I like coding and writing blog!!!");}var per1 = new Person("dwqs",20,"www.ido321.com");alert(per1.name); //dwqsvar per2 = new Person("i94web",22,"www.i94web.com");alert(per2.blog); //www.i94web.com
The constructor defines different attributes of each instance. The prototype shares common methods and attributes to maximize memory savings.
5. Dynamic Prototype
function Person(name,age,blog){ this.name = name; this.age = age; this.blog = blog; if(typeof this.interest != "function") { Person.prototype.interest = function() { alert("I like coding and writing blog!!!"); }; }}var per1 = new Person("dwqs",20,"www.ido321.com");per1.interest(); //I like coding and writing blog!!!
Encapsulate all information in the constructor and initialize the prototype as needed.
6. Parasitic constructor Mode
function Person(name,age,blog){ var o = new Object(); o.name = name; o.age = age; o.blog = blog; o.interest = function() { alert("I like coding and writing blog!!!"); } return o;}var per1 = Person("dwqs",20,"www.ido321.com");alert(per1.name); //dwqs
The format is the same as the factory mode, but this can be used in special cases to create constructors for objects and create objects using the new operator, while the factory mode does not use new, directly use the returned objects. For example, if you cannot modify the native object Array, add a new method to it.
function SpecialArray(){ var values = new Array(); values.push.apply(values,arguments); values.toPipedString = function() { return this.join("|"); }; return values;}var colors = new SpecialArray("red","blue","yellow");alert(colors.toPipedString()); //red|blue|yellow
It should be noted that the objects returned by the parasitic constructor mode have no relationship with the prototype objects of the constructor or constructor, so the instanceof operator cannot be used to determine the object type.
7. Safe Construction of the Function Model
function Person(name,age,blog){ var o = new Object(); o.sayName = function() { alert(name); } return o;}var per1 = Person("dwqs");per1.sayName(); //dwqs
Except for the sayName () method, there is no way to access the value of name for the object created in this way. Per1 is a secure object. A secure object is an object that does not have a public attribute and its method does not reference this.
The safe constructor mode differs from the parasitic constructor in two ways: the instance method of the new object does not reference this; the new operator is not used to call the constructor.
First: http://www.ido321.com/1365.html