First, understand the object:
First type: Object-based
New Object ();
' My Name ';
Person.age = 18;
function () {
THIS.name;
}
Second: The object literal way (a more clear Lookup object contains the properties and methods)
var person = {
' My name ',
Age:18,
function () {
THIS.name;
}
}
JS objects can use the '. ' operator to dynamically extend its properties, you can use the ' delete ' operator or set the property value to ' undefined ' to delete the property. As follows:
Person.newatt= 'new Attr '; Add Property
alert (Person.newatt); //new Attr
Delete Person.age;
alert (person.age);//undefined (the value is undefined after deleting the attribute);
Second, the object property type
ECMA-262 5th Edition Defines the attributes of JS objects (for JS engines, which cannot be accessed directly externally). There are two types of properties in ECMAScript: Data properties and accessor properties
1. Data attributes:
A Data property is a location that contains a data value that can be read or written to a value that has 4 attributes for its behavior:
[[Configurable]]: Indicates whether the delete operator can be removed to redefine, or whether it can be modified as an accessor property. The default is true;
[[Enumberable]]: Indicates whether the property can be returned through a for-in loop. Default true;
[[writable]]: Indicates whether the value of the property can be modified. Default true;
[[Value]]: Contains the data value for this property. Read/write is the value. The default is undefined, such as the name attribute defined in the instance object person above, whose value is ' My name ', and the modification of the value is in this position anyway
To modify the default characteristics of an object property (which is true by default), call the Object.defineproperty () method, which receives three parameters: the object where the property resides, the property name and a descriptor object (must be: configurable, enumberable, Writable and value, you can set one or more values).
as follows : (Browser support: ie9+, Firefox 4+, Chrome, safari5+)
var person = {};
' Name ', {
False
False
' Jack '
});
alert (person.name); //jack
Delete Person.name;
' Lily ';
alert (person.name);//jack
As you can see, the value of delete and reset Person.name is not in effect because the call to DefineProperty function modifies the properties of the object; It is worth noting that once the configurable is set to False, You can no longer use DefineProperty to modify it to true (execution will error: can ' t redefine non-configurable property);
2. Accessor properties:
It mainly consists of a pair of getter and setter functions, when the accessor property is read, the getter is called to return a valid value, when the accessor property is written, the setter is called, the new value is written, and the property has the following 4 characteristics:
[[[Configurable]]: can be deleted by the delete operator to remove the redefined property;
[[Numberable]]: Whether the property can be found through the for-in loop;
[[Get]]: Called when the property is read, default: undefined;
[[Set]: Called when writing properties, default: undefined;
Accessor properties cannot be defined directly and must be defined using DefineProperty (), as follows:
var person = {
_age:18
};
' Isadult ', {
function () {
if (this._age >= 18) {
True
else {
False
}
}
});
Alert (person.isadult? ') Adult ': ' minor ');//Adult
From the above, the getter and setter functions are not required to define the accessor properties, and the configurable and writable properties of the property cannot be specified when the getter and setter are defined;
In addition, ECMA-262 (5) provides a object.defineproperties () method that can be used to define properties of multiple properties at once:
var person = {};
Object.defineproperties (person,{
_age:{
Value:19
},
isadult:{
function () {
if (this._age >= 18) {
True
else {
False
}
}
}
});
Alert (person.isadult?') Adult ':' minor ');//adult
The above code uses the Object.defineproperties () method to define the properties of the two properties of the _age and ISAUDLT.
In addition, the properties of a given property can be obtained using the Object.getownpropertydescriptor () method:
var descriptor = Object.getownpropertydescriptor (person,' _age ');
alert (descriptor.value);//19
For data attributes, you can obtain: configurable,enumberable,writable and value;
For accessor properties, you can get: Configurable,enumberable,get and set
Iii. creating objects
Objects can be created using the object constructor or object literal, but the disadvantage is that when you create multiple objects, there is a lot of duplicate code, so here's how to create an object that solves the problem
1. Factory mode
function Createperson (name, age, Job) {
New Object ();
O.name = name;
O.age = age;
O.job = job;
function () {
THIS.name;
}
return o; //Return the generated object instance using return
}
var person = Createperson (' software Engineer ');
The creation of an object is given to a factory method, which can pass parameters, but the main disadvantage is that the object type is not recognized because the object is created using the native constructor of object.
2. Constructor mode
function Person (name,age,job) {
THIS.name = name;
This.age = age;
This.job = job;
function () {
THIS.name;
}
}
var person1 = New Person (' Jack ', ' n ', ' software Engineer ');
var = new Person (' liye ', Person2, ' mechanical Engineer ');
Define the properties and methods of the object type (for example, person) by using a custom constructor (just like a normal function, which is used only to create objects). It differs from the factory approach in that:
- Object not explicitly created
- Assigning properties and methods directly to the This object;
- no return statement;
In addition, to create an instance of person, you must use the new keyword, the person function as the constructor, pass parameters to complete the object creation, and actually create the following 4 procedures:
- Create an Object
- Assigns the scope of the function to the new object (so this point points to the new object, such as: Person1)
- Code to execute the constructor
- Returns the object
The above two objects generated by the person constructor Person1 and Person2 are instances of person, so you can use instanceof to judge, and because all objects inherit object, Person1 instanceof Object also returns true:
Alert (person1 instanceof person); //true;
Alert (person2 instanceof person); //true;
Alert (Person1 instanceof Object); //true;
Alert (Person1.constructor = = = Person2.constructor);//ture;
Although the constructor approach is good, there are drawbacks, that is, when creating an object, specifically for the object's properties point to the function, will be repeatedly created function instances, based on the above code, can be rewritten as:
function Person (name,age,job) {
THIS.name = name;
This.age = age;
This.job = job;
The new Function () {//overwrites the same effect as the original code, but for ease of understanding
THIS.name;
}
}
The code above, when creating multiple instances, calls the new function () repeatedly, creating multiple instances of the function that are not yet a scope, and of course this is not a mistake, but it can cause memory waste. Of course, a reference to GetName = GetName can be defined in the function, and the GetName function is defined outside the person, which resolves the problem of repeating the creation of the function instance, but the effect does not encapsulate the effect as follows:
function Person (name,age,job) {
THIS.name = name;
This.age = age;
This.job = job;
This.getname = GetName;
}
function GetName () {//Everywhere is code, look at the mess!!
THIS.name;
}
3. Prototype mode
JS each function has a prototype (prototype) attribute, which is a pointer to an object, which is the prototype object for all instances created with the function using the new operator. The most important feature of a prototype object is that all object instances share the properties and methods it contains, that is, all properties or methods created in the prototype object are shared directly by all object instances.
function person () {
}
' Jack ';//Use prototypes to add attributes
Person.prototype.age = 29;
function () {
THIS.name;
}
New Person ();
Alert (Person1.getname ()); //jack
New Person ();
Alert (Person1.getname = = = Person2.getname);//true; method of sharing a prototype object
The prototype is pointing to the prototype object, which is not much related to the constructor, and the only relationship is that the prototype of the function is pointing to the prototype Object! An object instance created based on a constructor also contains an internal pointer to: [[prototype]] pointing to the prototype object.
The access procedure for an instance property or method is a search process:
- First, start with the object instance itself, and return the property value directly if it is found;
- If the instance itself does not exist to find the attribute, continue searching for the prototype object pointed to by the pointer, in which to find the property of the given name, and return if there is one;
Based on the above analysis, the prototype schema creates an object instance whose properties are shared with the prototype object, but can be defined in its own instance, not from the prototype object when it is searched, but rather by the search principle, which is the property in the instance that masks the properties in the prototype object;
Prototypes and in Operators
Bottom line: Regardless of the properties in the prototype or the properties of the object instance, you can use the in operator to access it, and to determine whether the property of the instance itself can be judged by using Object.hasownproperty (' attr ');
Prototype in native object
The prototype in the native object is like a prototype of a normal object, you can add/modify properties or methods, such as the following code to add a left and right blank prototype method for all string objects:
function () {
This.replace (/^\s+/, "). Replace (/\s+$/,");
}
' word space ';
Alert ('! ') +str.trim () +'! '); /!word space!
The disadvantage of prototype mode is that it omits to pass initialization parameters for the constructor, which is inconvenient in certain procedure, and the most important thing is that when the object's property is a reference type, its value is constant, always referencing the same external object, all instances of the operation of the object will be other instances:
function person () {
}
' Jack ';
Person.prototype.lessons = [' Math ',' Physics '];
New Person ();
Person1.lessons.push (' biology ');
New Person ();
alert (person2.lessons);//math,physics,biology,person1 modification affects the Person2
4.combinatorial constructors and prototype patterns
The most commonly used method of defining type is the combination of constructor pattern and prototype pattern. The constructor pattern is used to define the properties of the instance, whereas the prototype pattern is used to define methods and shared properties. As a result, each instance will have its own copy of the instance properties, but at the same time share a reference to the other method, maximizing memory savings. In addition, the combination mode supports passing parameters to the constructor, which is the director of the two family.
function person (name, age, Job) {
THIS.name = name;
This.age = age;
This.job = job;
This.lessons = [' Physics '];
}
Person.prototype = {
Constructor:person,//prototype literal will change the object's constructor into object, and also force the person to refer back to the person
function () {
THIS.name;
}
}
New Person (' software engneer ');
Person1.lessons.push (' biology ');
New Person (' mechanical engneer ');
alert (person1.lessons); //math,physics,biology
alert (person2.lessons); //math,physics
Alert (Person1.getname = = = Person2.getname);//true,//Shared prototype definition method
in the Contact JS Library, the jquery type of encapsulation is used in combination mode to instance!!!
5. Dynamic prototype mode
The instance properties in the composition mode are separated from the shared method (defined by the prototype), which is not consistent with the pure object-oriented language, and the dynamic prototype pattern encapsulates all the construction information in the constructor and preserves the advantages of the combination. The principle is to determine whether a shared method or property has been defined in the prototype of the constructor, and if not, the definition process is no longer performed. The method is only defined once on the prototype, and all construction procedures are encapsulated in the constructor, and modifications to the prototype are immediately reflected in all instances:
function person (name, age, Job) {
THIS.name = name;
This.age = age;
This.job = job;
This.lessons = [' Physics '];
}
if (' function ') {//By judging instance encapsulation
Person.prototype = {
Constructor:person,//prototype literal will change the object's constructor into object, and also force the person to refer back to the person
function () {
THIS.name;
}
}
}
New Person (' software engneer ');
Person1.lessons.push (' biology ');
New Person (' mechanical engneer ');
alert (person1.lessons); //math,physics,biology
alert (person2.lessons); //math,physics
Alert (Person1.getname = = = Person2.getname); //true,//defining methods in shared prototypes
Object-oriented programming in JS