Watch the object-oriented JavaScript

Sometimes we use the computer, do not know what it is the principle, but that he will use, which is object-oriented. Similarly, in JavaScript can also use this principle, then just let me explore together what object-oriented JavaScript content on it.

Process overview for programming and object-oriented programming is the procedure for the step of analyzing the problem, and then using a step function to implement these steps, focus on each process is completed. Object-oriented package is based on the idea, the problem analysis data obtained encapsulated into one object, then the corresponding function is accomplished by the operation of the object. For chestnut: Cook cooking process-oriented thought to be analyzed into the following steps: 1. Check the ingredients are complete enough 2. If not, the jolly fire 3. 4. 5. cooking vegetables (in the order of ingredients into the appropriate, spices, etc.) thought to pan plate 6. the object-oriented analysis is this: 1. cooks, food inspection, 2. cooking buyer, jolly 3. baidunzi, vegetables, vegetable, to complete the cooking of dishes prepared by the method of calling behavior of the entire process above object can be seen from the above example, object-oriented and process-oriented biggest difference is that, by the object-oriented interest which objects, each of which features should have, and process-oriented concern is the implementation process of each step. So these two ideas in the end it is better? On the surface, looks like a better object-oriented, why? Because it is fully in line with our normal way of thinking, so in terms of acceptance, object-oriented thinking is definitely better. However, there are process-oriented his advantage, that is flexible and convenient, relatively speaking will be more consumption of resources, but a little slower object-oriented. So, as to what kind of future use, which we need to look at specific needs, make different choices based on different needs. Object-oriented programming concepts through the above analysis, we know that the object-oriented package focuses on functional analysis and objects, then eventually we get the structure of the object is what we continue to learn down. For example, my analysis of the people get, everyone has a name, age, sex and other attributes, but also to eat and sleep and other acts, then use JS can do the following packages: var p = {name: "xiao song", age : 10, sex: 1, eat: function () {console.log ( "food");}, sleep: function () {console.log ( "sleep");}} console.log (p.name); Access to the object attribute p.eat // (); // Method to access the object above the p represents an object, wherein the method attribute name / age / sex called objects, eat / sleep called objects, we aim to achieve by accessing the appropriate property or method of the object. After reviewing DOM operations related knowledge in learning html We've found html document is actually composed by a bunch of labels, due later in the course need to use html, so let's review a rough look at its structure.

H5-JS object-oriented

div h3: element node id class: attribute node H5-JS object-oriented: text nodes a html document mainly composed of three parts, the DOM (Document Object Model) is a property or method this element operating the package, so as to achieve easy html purpose of efficient operation. Gets the element object: Property document.getElementById ( "div1") to access elements: div1.className access the elements of text: div1.innerText CRUD elements: div1.appendChild (newNode) Now, we passed these instructions are intended to explain API content-related objects. Create and set the label (process-oriented)
Requirement 1: Create three div element, and set the border, background color, text font color, and for (var i = 0; i <3; i ++) {var div = document.createElement ( "div"); div.innerText = "div" + i; div.style.backgroundColor = "green"; div.style.border = "1px solid # 000"; div.style.color = "white"; document.body.appendChild (div);}! [insert picture described herein] (https://img-blog.csdnimg.cn/20191220094107944.jpeg)
Requirement 2: Set border, background color, text font and color for the three P element in the page exists

I was P1

I was P2

I was P3

Demand 3: Get three class = "test" elements on the page, set borders, background color, text color and font

I was heading 1

I was heading 2

I was heading 3

 

 

The code above is based on process-oriented thinking is completed, you can see both the needs of each step is our complete step by step, the problem is obvious, the code is a lot of redundancy, this post-code is bad maintenance. Create and set the label (function package) to repeat the above code, we can use the function package be

 

Package three functions:

  1. setStype (eles, bgcolor): Set the style element
  2. eles: which elements
  3. bgcolor: background color
  4. getElementsByTagName (tagName): Gets the specified elements based on the element name
  5. tagName: element name
  6. getElementsByClassName (className): Gets the specified elements based on the class attribute name
  7. className: class attribute name
    1. The next step is to call three methods to complete the above requirements, to solve the problem in the first way a lot of duplicate code. However, this approach remains problematic. In front of the JS Foundation said that we should try to avoid heavy use of global variables, which reduces the efficiency of the implementation of the program, the above program, we appeared five (including function). It is necessary to continue to optimize. Create and Settings tab (object-oriented) use of object-oriented thinking to solve the above problem, we can be above three functions are packed into an object var  = {
setStype:function (eles,bgcolor) {
    for (var i = 0; i < eles.length; i++) {
        eles[i].style.backgroundColor=bgcolor;
        eles[i].style.border="1px solid #000";
        eles[i].style.color="white";
    }
},
getElementsByTagName: function (tagName) {
    return document.getElementsByTagName(tagName);
},
getElementsByClassName:function (className) {
    return document.getElementsByClassName(className);
}
}var ps =.getElementsByTagName ( "the p-") .setStype(ps,"green");var tests=.getElementsByClassName ( "the Test"); .setStype (tests, "red"); later if we need to encapsulate other functions, can be directlythis the object is added to obtain the element according to the id attribute of the element, which is not set style getElementById: function (eleId) {return [document.getElementById (eleId)];} Note that, in the styling process, we the default is the element passed in as array processing, so here we getElementById method, the manual will get to add an element to the array returned. By observation,Subject, there is a method obtaining three elements, here we better to classify the following manner var= {GetElements: {byTagName: function (tagName) {return document.getElementsByTagName (tagName);}, byClassName: function (className) {return document.getElementsByClassName (className);}, byId: function (eleId) {return [document. getElementById (eleId)];}}, setStype: function (eles, bgcolor) {for (var i = 0; i <eles.length; i ++) {eles [i] .style.backgroundColor = bgcolor; eles [i]. style.border = "1px solid # 000"; eles [i] .style.color = "white";}}} the method for obtaining the element package to $ getElements object attribute, if there is another method to get the next element , should be added to getElements properties, other types of encapsulation methods should follow this idea. Three characteristics of object-oriented programming object-oriented features: the role of packaging: multiplexing information hiding and encapsulation, which is the objective things packaged as an abstract class, and the class can put their data and methods only allow trusted classes or objects operation of unreliable information hiding. It can use all the features inherit an existing class, and without having to rewrite these functions extend the case of the original class. Create a new class by inheriting called "sub-class" or "derived class." Inherited classes are called "base class", "parent" or "superclass." Succession process, that is, from the general to the particular process. When polymorphism exists as inheritance, the parent class object allowed and seen as one of its equivalents or more sub-class object. In this manner, can be operated in accordance with the particular characteristics of the current sub-object of the parent class object is assigned in different ways. Objects created with literal way to create an object using the literal direct comparisons embodiment, the format of the key data defined var book1 = {name: "JavaScript Definitive Guide", price: 100, author: "tim", showInfo: function () {console.log (this.name, this.price, this.author);}} console.log (book1); a book object defined above, and add properties and methods, we can directly access wherein the attributes and methods. The drawbacks of this approach is that if you need to create multiple similar objects, it is not very convenient, a lot of duplicate code will appear. In other words, this approach is not suitable for creating a large number of the same or similar object. Built-in constructors and create objects simple factory to create an object var book2 = new Object () using the new keyword + built-in constructor; book2.name = "JS"; book2.price = 10; book2.author = "author"; book2 .showInfo = function () {console.log (this.name, this.price, this.author);} book2.showInfo (); in this way the presence and create objects literal manner similar problems, the object of creating a large number of when there will be a lot of duplicate code. Then, using the ideological front of the package, we should be able to expect that when there are duplicate code, we can repeat these codes drawn into the function to resolve. function createBook (name, price, author) {var book = new Object (); book.name = name; book.price = price; book.author = author; book.showInfo = function () {console.log (this. name, this.price, this.author); } Return book;} var book3 = createBook ( "bookName1", 10, "author1"); var book4 = createBook ( "bookName2", 10, "author2"); console.log (book3); console.log (book4) ; we will create the code book objects encapsulate createBook function, when you need to create a book when the object directly call the function, the function will need to pass parameters to the past. Well, the same idea, if we need to create other objects, you can use the same method to solve the wrapper function, this is no problem. function createPerson (name, age) {var p = new Object (); p.name = name; p.age = age; return p;} console.log (createPerson ( "Neld", 10)) using the above function, we can create a Person object out, but through print contrast, we can not determine the type of the object by object creation out, but in the actual development, determine the type of the object is, we often need to perform, so we continue to look below self define a constructor to create the object. Constructor creates a custom object constructor function and general definition exactly the same way, the following, we define a constructor to create Person function createPerson (name, age, sex) {this.name = name; this.age = age; this.sex = sex;} var p = new createPerson ( "Neld", 10, 1); var p2 = new createPerson ( "Song", 12, 0); console.log (p); console.log (p2) ;
  8. The first letter of the name of the constructor capital requirements
  9. Need to use the new keyword and constructor creates objects together
  10. In the function, not need to manually create the object to be encapsulated, and the encapsulated data is automatically created
  11. In the last function, without having to manually create good returns an object, it will automatically return to here, we are sure there will be questions, how in the end is to create a custom constructor and package objects?
  12. Inside the function creates a default empty object var obj = new Object ();
  13. The default assignment to create a good object to this this = obj;
  14. The default setting of this prototype object for the current prototype object constructor
  15. By this add properties and methods
  16. Objects created internal default will return to return this; Through the above analysis, I believe we have been able to understand the basic use a custom constructor and basic principles of the. Constructor creates object returns default value, the function returns the internal structure of the newly created good object (this) initiative Returns:
  17. If the value of the type of data returned, still returns the created objects (this), without any modification
  18. If the return type of the reference data, the specified data is returned, not to return this. Function as a constructor parameter in the JS world, the function belongs to the first-class citizens, with the most privileged, as you can assign values ​​to variables in use, can be passed as parameters, can be used as the return value of the function, let's take a look at his specific usage of. Function uses the function f1 (name, age, fn) as parameters {console.log ( "name:", name, "age:", age); fn ();} function fn () {console.log ( "Hello H5 ");} f1 (" Neld ", 10, fn); output: name: Neld age: 10 Hello H5 in the above code, the function fn will be passed as a parameter to the function f1, and the function f1 call corresponding printout obtained. As a function of return value of function f1 (name, age, fn) {console.log ( "name:", name, "age:", age); return fn;} function fn () {console.log ( "Hello H5 ");} var retFun = f1 (" Neld ", 10, fn); retFun (); passed in a function f1 in the Fn returned as a return value, to return to after receiving the call to the function f1 is worth returning to and then call retFun get print results. At this time, the function f1 is a higher order, i.e., one or more parameters is a function, and the function as a return value. At this time, the callback function fn, fn passed as a parameter to a function f1, called internally f1. Function is used as the argument to the constructor function createPerson (name, age, sex, say) {this.name = name; this.age = age; this.sex = sex; this.say = say; } Var p = new createPerson ( "Neld", 10, 1, function () {console.log ( "say hello");}); var p2 = new createPerson ( "Song", 12, 0, function () { console.log ( "say bye");}); p.say (); p2.say (); method may be encapsulated in the constructor, if the implementation of the method is determined by the caller, it can be receiving a constructor function object, and then encapsulated in the constructor. The above function say, and assigned to the transmitted parameter p and say p2 when creating the object, and then assigned to the current object in the constructor. Speaking in front of property plant constructor function to create an object is more convenient, but there is a problem that can not be created out of that type of object, so we chose to use the constructor to create a custom constructor to create an object we can already use , then learn how to create an object type by him? Here we offer two ways. It may be performed in the constructor method of the package, if the implementation of the method is determined by the caller, then the object may receive a constructor function, and then encapsulated in the constructor. The above function say, and assigned to the transmitted parameter p and say p2 when creating the object, and then assigned to the current object in the constructor. Speaking in front of property plant constructor function to create an object is more convenient, but there is a problem that can not be created out of that type of object, so we chose to use the constructor to create a custom constructor to create an object we can already use , then learn how to create an object type by him? Here we offer two ways. It may be performed in the constructor method of the package, if the implementation of the method is determined by the caller, then the object may receive a constructor function, and then encapsulated in the constructor. The above function say, and assigned to the transmitted parameter p and say p2 when creating the object, and then assigned to the current object in the constructor. Speaking in front of property plant constructor function to create an object is more convenient, but there is a problem that can not be created out of that type of object, so we chose to use the constructor to create a custom constructor to create an object we can already use , then learn how to create an object type by him? Here we offer two ways.
  19. constructor property

function Person (name) {this.name = name;} function Dog (name) {this.name = name;} var p = new Person ( "p"); var d = new Dog ( "d"); console. log (p.constructor); // get Person print function object the console.log (d.constructor); // get Dog print function object if (p.constructor == Person) {console.log ( " Person object is") ;} if (d.constructor == Dog) {console.log ( " Dog object is");} property to get 3. constructor function object constructor to create an object for use, so we can by determining the type constructor to know the type of object created 4.

  1. instanceof keyword
  2. function Person(name) { this.name = name; }function Dog(name) { this.name = name; }var p = new Person("p");var d = new Dog("d");console.log(p instanceof Person);//trueconsole.log(d instanceof Person);//false
  1. instanceof keyword can be directly used determine the type of the object, if the type is specified, returns true, and vice versa returns false.

Call the constructor and named after studying the constructor, and some students to distinguish it from ordinary functions still not clear, here we are again make a note of the constructor. 1. constructor function and there is no difference in the general definition syntax 2. function function name (parameter list) {code block;} 3 and 4. In order to distinguish a normal function, we agreed to name in the constructor of the upper case 5 Like 6. constructor can be called directly, this time inside the execution of this window, this way is not safe, it is possible to modify the current global variables inside a function, not recommended, but doing so also can not create object 7. 8. want to create an object, you must use the constructor new and used with 9 function pointer found in this context and the process of JS programming, we use a lot to this keyword, make good use of this, we can make the code more elegant . this is always performed to an object (reference type), but who perform specific, we need to use this where relevant. Here are divided into the following situations:

  1. External function
  2. Is outside the scope function global scope (window), so that the overall effect of this use of the domain pointing window
  3. General internal function
  4. Inside the function scope is local, belonging to the calling object is the current function, so this current executive to call the object function
  5. Internal Constructor
  6. In the constructor, this direct implementation of new objects created out of the current
  7. In development, we can also use call or apply a function to modify the execution of this, which we continue to be described later. Since there is the problem of the definition of a constructor custom constructor can solve the problems caused by factory function object type of uncertainty in the development with very much, so now we custom constructor and whether there is a problem? Let's look at the following object memory structure analysis. function Person (name, age, say) {this.name = name; this.age = age; this.say = function () {console.log ( "say hello");}} var p = new Person ( "zs ", 10, say); console.log (p); p memory structure of FIG objects created above:


 

 

 

  1. As can be seen, we did not create a Person object, such as 0x22 and 0x33 are assigned such a memory to store data in memory, but the observation that, 0x33 is stored in a function, and this function is in each object the same

 

 

 

 

So from the memory resource allocation considerations, we do not need to create and assign a new function object (identical) for each object, this function it had better share the same copy. How to achieve multiple objects share the same data it, which requires the use of knowledge related to the prototype point.

 

So from the memory resource allocation considerations, we do not need to create and assign a new function object (identical) for each object, this function it had better share the same copy. How to achieve multiple objects share the same data it, which requires the use of knowledge related to the prototype point.

 

Guess you like

Origin www.cnblogs.com/waiwei/p/12079721.html