In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly shows you the "sample analysis of JS object-oriented programming", which is easy to understand and well-organized. I hope it can help you solve your doubts. Let the editor lead you to study and study the "sample analysis of JS object-oriented programming".
Object-oriented language has a sign, that is, it has the concept of class, abstracts the common properties and methods of instance objects, and can create any number of instance objects based on the class, which generally has the characteristics of encapsulation, inheritance and polymorphism. But objects in JS are different from objects in pure object-oriented language. ECMA standard defines objects in JS: a collection of unordered attributes, whose properties can contain basic values, objects, or functions. An object that can be simply understood as JS is an unordered set of values in which all properties or methods have a name according to which the mapped value can be accessed (the value can be a base value / object / method).
First, understand the object:
First: based on Object object
Var person = new Object (); person.name ='My Name';person.age = 18scape person.getName = function () {return this.name;}
The second: the literal quantity of the object (to find the properties and methods contained in the object more clearly)
Var person = {name:'My name', age: 18, getName: function () {return this.name;}}
Objects in JS can use'.' The operator dynamically extends its properties, which can be deleted using the 'delete' operator or by setting the property value to' undefined'. As follows:
Person.newAtt='new Attr';// add attribute alert (person.newAtt); / / new Attrdelete person.age;alert (person.age); / / undefined (undefined after attribute deletion)
II. Object attribute types
ECMA-262 version 5 defines features in JS object properties (for JS engines, which are not directly accessible from the outside). There are two types of properties in ECMAScript: data properties and accessor properties
1. Data attributes:
A data attribute refers to a location that contains a data value where the value can be read or written, and the attribute has four properties that describe its behavior:
[[configurable]]: indicates whether it can be deleted and redefined using the delete operator, or can be modified to an accessor property. Default is true
[[Enumberable]]: indicates whether a 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 of this attribute. Read / write is this value. The default is undefined;. For example, the name attribute is defined in the above instance object person, and its value is'My name',. All changes to this value are in this position.
To modify the default characteristic of an object property (default is true), call the Object.defineProperty () method, which takes three parameters: the object in which the property resides, the property name, and a descriptor object (must be: configurable, enumberable, writable, and value, which can set one or more values).
As follows: (browser support: IE9+, Firefox 4 +, Chrome, Safari5+)
Var person = {}; Object.defineProperty (person, 'name', {configurable: false, writable: false, value:' Jack'}); alert (person.name); / / Jackdelete person.name;person.name = 'lily';alert (person.name); / / Jack
You can see that the values of delete and reset person.name do not take effect, because calling the defineProperty function modifies the characteristics of the object properties; it is worth noting that once configurable is set to false, it can no longer be changed to true using defineProperty (error will be reported by execution: can't redefine non-configurable property)
2. Accessor properties:
It mainly consists of a pair of getter and setter functions, which call getter to return a valid value when the accessor property is read, and setter to write the new value when the accessor property is written, which has the following four characteristics:
[[Configurable]]: whether redefined attributes can be deleted through the delete operator
[[Numberable]]: whether this property can be found through the for-in loop
[[Get]]: called when reading attributes. Default: undefined.
[[Set]]: called when a property is written. Default: undefined
Accessor properties cannot be defined directly, but must be defined using defineProperty (), as follows:
Var person = {_ age: 18}; Object.defineProperty (person, 'isAdult', {get: function () {if (this._age > = 18) {return true;} else {return false;}}); alert (person.isAdult?' Adult': 'underage'); / / Adult
As can be seen from the above, the getter and setter functions are not required when defining accessor properties, and the configurable and writable properties of properties cannot be specified when defining getter and setter.
In addition, ECMA-262 (5) provides an Object.defineProperties () method that can be used to define the properties of multiple attributes at once:
Var person = {}; Object.defineProperties (person, {_ age: {value:19}, isAdult: {get: function () {if (this._age > = 18) {return true;} else {return false;}); alert (person.isAdult?' Adult': 'underage'); / / Adult
The above code uses the Object.defineProperties () method to define the properties of both the _ age and isAudlt properties
In addition, you can get the properties of a given property using the Object.getOwnPropertyDescriptor () method:
Var descriptor = Object.getOwnPropertyDescriptor (person,'_age'); alert (descriptor.value); / / 19
For data attributes, you can get: configurable,enumberable,writable and value
For the accessor properties, you can get: configurable,enumberable,get and set
Third, create objects
You can create objects using either the Object constructor or object literals, but the disadvantage is that creating multiple objects will result in a lot of duplicate code, so here's how to create objects that can solve this problem.
1. Factory mode
Function createPerson (name, age, job) {var o = new Object (); o.name = name; o.age = age; o.job = job; o.getName = function () {return this.name;} return oop / use return to return the generated object instance} var person = createPerson ('Jack', 19,' SoftWare Engineer')
Object creation is left to a factory method, and parameters can be passed, but the main disadvantage is that the object type is not recognized, because object creation is done using Object's native constructor.
2. Constructor model
Function Person (name,age,job) {this.name = name; this.age = age; this.job = job; this.getName = function () {return this.name;}} var person1 = new Person ('Jack', 19,' SoftWare Engineer'); var person2 = new Person ('Liye', 23,' Mechanical Engineer')
Use custom constructors (like normal functions, only to create objects) to define properties and methods of object types (such as: Person). It differs from the factory approach in:
Objects are not explicitly created
Assign 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, use the Person function as the constructor, and pass parameters to complete the object creation. The actual creation goes through the following four processes:
Create an object
Assign the scope of the function to the new object (so this points to the new object, such as person1)
Code that executes the constructor
Return to the object
The above two objects, person1 and person2, generated by the Person constructor, are both instances of Person, so you can use instanceof to determine, 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 method is quite good, it also has some disadvantages, that is, when creating an object, especially when the attribute of the object points to the function, the function instance will be created repeatedly. Based on the above code, it can be rewritten as follows:
Function Person (name,age,job) {this.name = name; this.age = age; this.job = job; this.getName = new Function () {/ / the rewritten effect is the same as the original code, but to facilitate the understanding of return this.name;}}
In the above code, when multiple instances are created, new Function () is called repeatedly; multiple function instances are created, and these function instances are not in the same scope, of course, there is nothing wrong with this, but it can lead to memory waste. Of course, you can define a reference of getName = getName in the function, while the getName function is defined outside the Person, which can solve the problem of repeatedly creating function instances, but it does not have the effect of encapsulation, as shown below:
Function Person (name,age,job) {this.name = name; this.age = age; this.job = job; this.getName = getName;} function getName () {/ / there is code everywhere, it looks messy! Return this.name;}
3. Prototype model
Each function of JS has a prototype property, which is a pointer to an object, which is the prototype object of all instances created using functions through the new operator. The most important feature of the 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 directly shared by all object instances.
Function Person () {} Person.prototype.name = 'Jack';// uses the prototype to add the attribute Person.prototype.age = 29scape Person.prototype.getName = function () {return this.name;} var person1 = new Person (); alert (person1.getName ()); / / Jackvar person2 = new Person (); alert (person1.getName = person2.getName); / / true; 's method of sharing a prototype object
The prototype points to the prototype object, which does not have much to do with the constructor, the only relationship is that the function's prototype points to the prototype object! The object instance created based on the constructor also contains an internal pointer: [[prototype]] to the prototype object.
The access to an instance property or method is a search process:
Start with the object instance itself, and return the property value directly if the property is found
If the instance itself does not have a property to find, continue to search for the prototype object that the pointer points to, find the property with the given name, and return if any
Based on the above analysis, the properties of the object instances created by the prototype pattern share the prototype objects, but they can also be defined in their own instances. When searching, they are not obtained from the prototype objects, but are returned according to the search principles. To put it simply, the properties in the instance will block the properties in the prototype objects.
Prototypes and in operators
In a word: both the properties in the prototype and the properties of the object instance can be accessed using the in operator; to determine whether it is a property of the instance itself, you can use object.hasOwnProperty ('attr') to determine
Prototypes in native objects
Prototypes in native objects, like prototypes in ordinary objects, can add / modify properties or methods, such as the following code to add left and right blank prototype methods for all string objects:
String.prototype.trim = function () {return this.replace (/ ^\ s). Replace (/\ s));} var str = 'word space'; alert ('!'+ str.trim () +'!); / /! word space!
The disadvantage of the prototype pattern is that it omits passing initialization parameters for the constructor, which brings inconvenience to certain programs; in addition, the most important thing is that when the property of an object is a reference type, its value is unchanged and always refers to the same external object. all instances operate on the object in other instances:
Function Person () {} Person.prototype.name = 'Jack';Person.prototype.lessons = [' Math','Physics']; var person1 = new Person (); person1.lessons.push ('Biology'); var person2 = new Person (); alert (person2.lessons); / / Math,Physics,Biology,person1 modification affected person2
4. Combinatorial constructor and prototype pattern
At present, the most commonly used way to define types is to combine constructor patterns and prototype patterns. The constructor pattern is used to define the properties of the instance, while the prototype pattern is used to define methods and shared properties. As a result, each instance will have its own copy of instance properties, but at the same time share references to each other's methods, maximizing memory savings. In addition, the combination mode also supports the passing of parameters to the constructor, which can be said to be the best of both.
Function Person (name, age, job) {this.name = name; this.age = age; this.job = job; this.lessons = ['Math',' Physics'];} Person.prototype = {constructor: Person,// prototype literally changes the object's constructor to Object, and forces Person getName: function () {return this.name;}} var person1 = new Person ('Jack', 19,' SoftWare Engneer'); person1.lessons.push ('Biology') Var person2 = new Person ('Lily', 39,' Mechanical Engneer'); alert (person1.lessons); / / Math,Physics,Biologyalert (person2.lessons); / / Math,Physicsalert (person1.getName = person2.getName); / / method defined in the true,// shared prototype
In the JS library you come into contact with, the encapsulation of the jQuery type is instantiated using the composite pattern!
5. Dynamic prototype model
In the combination pattern, the instance properties are separated from the sharing method (defined by the prototype), which is not consistent with the pure object-oriented language; the dynamic prototype pattern encapsulates all the construction information in the constructor while maintaining the advantages of combination. The principle is to determine whether shared methods or properties have been defined in the prototype of the constructor, and if not, the definition will not be performed otherwise. In this way, the method or property on the prototype is defined only once, and all the construction processes are encapsulated in the constructor, and the changes made to the prototype can be immediately reflected in all instances:
Function Person (name, age, job) {this.name = name; this.age = age; this.job = job; this.lessons = ['Math',' Physics'] } if (typeof this.getName! = 'function') {/ / changes the constructor of the object to Object by judging that the instance encapsulates Person.prototype = {constructor: Person,// prototype literally, and forcibly refers back to Person getName: function () {return this.name;} var person1 = new Person (' Jack', 19, 'SoftWare Engneer'); person1.lessons.push (' Biology') Var person2 = new Person ('Lily', 39,' Mechanical Engneer'); alert (person1.lessons); / / Math,Physics,Biologyalert (person2.lessons); / / Math,Physicsalert (person1.getName = person2.getName); / / true,// shared prototype methods defined above are all the contents of the article "sample Analysis of JS object-oriented programming". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.