JavaScript Advanced Programming Study notes (5)-object-oriented programming

Source: Internet
Author: User

Welcome to my public number "front-end small fill", focus on the foundation of the front-end Technology and project development Learning.

The content of this section corresponds to the sixth chapter of the Advanced programming of Javascript.

1. object-oriented (object-oriented, OO) languages have a sign that they all have the concept of a class, and that a class can create any number of objects with the same properties and METHODS. As mentioned earlier, there is no concept of class in ecmascript, so its objects are also different from objects in class-based languages.

ECMA-262 defines an object As: " a collection of unordered attributes whose properties can contain basic values, objects, or functions ." "strictly speaking, This is equivalent to saying that the object is a set of values that do not have a particular order. Each property or method of an object has a name, and each name is mapped to a Value. Because of this (and other reasons to be discussed), we can think of the ECMAScript object as a hash table: nothing more than a set of name-value pairs where the value can be data or function .

Each object is created based on a reference type, which can be either the native type discussed earlier or a developer-defined type.

2. attribute type : ECMA-262 The 5th edition describes the various characteristics of a property when it defines an attribute that is only used Internally. ECMA-262 defines these features for the purpose of implementing JavaScript engines, so they are not directly accessible in Javascript. To indicate that the attribute is an intrinsic value, the specification places them in two opposing brackets, such as [[Enumerable]].

    • Data Properties : A location that contains a data value. Values can be read and written at this Location. The data attribute has four attributes that describe its Behavior.
      • [[Configurable]]: Indicates whether the property can be redefined by deleting the property from delete, can modify the Attribute's attributes, or can modify the property to an accessor Property. Properties that are defined directly on the object as in the previous example, their default value is True
      • [[Enumerable]]: Indicates whether the property can be returned through a for-in loop. Properties that are defined directly on the object, as in the previous example, have the default value of True for this Attribute.
      • [[writable]]: Indicates whether the value of the property can be Modified. Properties that are defined directly on the object, as in the previous example, have the default value of True for this Attribute.
      • [[Value]]: contains the data value for this Property. When reading a property value, read from this position, and when writing the value of the property, save the new value in this Position. The default value for this attribute is Undefined.

To modify the Property's default attributes, you must use the ECMAScript5 object.defineproperty () method . This method receives three parameters: the object where the property resides, the name of the property, and a descriptor Object. Where the property of the Descriptor object must be: configurable, enumerable, writable, and Value. Set one or more of these values to modify the corresponding attributes

var person = {          name:' Nicholas ', age          :,          toString:function  () {              returnThis this. age + "]";          }  };  " Name ", {      writable:false  });  Person.name= "goskalrie"; // Invalid  modification Alert (person); // [name=nicholas; age=29]

  • accessor properties: does not contain data values; they contain a pair of getter and setter functions (however, Neither of these functions is required). When the accessor property is read, The Getter function is called, which is responsible for returning a valid value, and when the accessor property is written, the setter function is called and the new value is passed IN. This function is responsible for deciding what to do with the Data. Accessor properties have the following 4 Attributes. accessor properties cannot be defined directly and must be defined using Object.defineproperty () .

    • [[configurable]]: indicates whether the property can be redefined by deleting the property from delete, can modify the Attribute's attributes, or can modify the property to a data Property. For properties defined directly on the object, the default value of this property is True

    • [[Enumerable]]: indicates whether the property can be returned through a for-in loop. For properties that are defined directly on the object, the default value of this property is True.

    • [[Get]]: the function that is called when the property is Read. The default value is Undefined.

    • [[Set]]: the function that is called when the property is Written. The default value is Undefined.

          varBook ={_year:2004, Edition:1      }; Object.defineproperty (book,"year", {get:function(){              return  this. _year; }, set:function(newvalue) {if(newvalue > 2004){                   this. _year =newvalue;  this. edition + = newValue-2004;      }          }      }); Book.year= 2005; Alert (book.edition);//2

  • Because of the high likelihood of defining multiple properties for an object, ECMAScript5 also defines aobject.defineproperties () Method。 This method allows you to define multiple properties at once by describing Them. This method receives two object arguments: the first object is the object whose properties are to be added and modified, and the properties of the second object correspond to the property one by one to be added or modified in the first Object. The following code defines two data attributes (_year and Edition) and an accessor attribute (year) on the Book.
    varBook = {}; Object.defineproperties (book, {_year:{value:2004}, edition:{value:1}, year:{get:function(){              return  this. _year; }, set:function(newvalue) {if(newvalue > 2004){                   this. _year =newvalue;  this. edition + = newValue-2004; }          }      }  }); 
  • attributes of Read attributes : using the ECMAScript5 object.getownpropertydescriptor () method , you can obtain a descriptor for a given Property. This method receives two parameters: the object where the property resides and the name of the property whose descriptor you want to READ. The return value is an object, and if it is an accessor property, the property of the object has configurable, enumerable, get, and set, and if it is a data property, the property of the image is configurable, enumerable, Writable and Value.

    var descriptor =object.getownpropertydescriptor (book, "_year");  Alert (descriptor.value); // 2004   Alert (descriptor.configurable); // false   Alert (typeof descriptor.get); // "undefined"

3. Create an object: although the object constructor or object literal can be used to create a single object, there are obvious drawbacks: creating many objects with the same interface creates a lot of duplicate code. Here's how to find more ways to create objects:

  • Factory Mode: Factory mode is a well-known design pattern in the field of software engineering that abstracts the process of creating concrete objects. Considering the inability to create a class in ecmascript, the developer invented a function that encapsulates the details of creating an object with a specific interface. The Factory mode solves the problem of creating multiple similar objects, but does not solve the problem of object recognition (that is, How to know the type of an Object) .

    function Createperson (name, age) {      varnew  Object ();       = name;       = Age ;       function () {          Alert (this. name);      };       return obj;  }   var person1 = Createperson ("Nicholas");   var person2 = Createperson ("Greg", 21);

  • constructor mode : as described earlier, constructors in ECMAScript can be used to create objects of a specific type. Native constructors, such as Object and array, will automatically appear in the execution environment at run Time. In addition, you can create custom constructors that define properties and methods for custom object Types. create an instance with a constructor, you must use the new operator . Note the differences between the Factory mode and the plant model.

    function person (name, age) {      this. name = name;        this. age = Age ;        this function () {          Alert (this. name);}      ;  }   var New Person ("Nicholas");   var New

  • The only difference between constructors and other functions is thatthey are called in different ways。 however, constructors are functions after all, and there is no special syntax for defining constructors. Any function, as long as it is called by the new operator, can be used as a constructor, and any function, if not called by the new operator, is no different from the normal Function.
     //  use  var  person = new  person ("Nicholas", 29 //     "Nicholas"  //     as a normal function Person ("Greg", 21); //  added to window  window.sayname (); //     "Greg"  var  o = new        Object ();      Person.call (o,  "goser", 24 //  "goser"  

      constructors are easy to use, but they are not without drawbacks. The main problem with constructors is that each method is recreated on each instance. In the previous example, both Person1 and Person2 have a method named Sayname (), but the two methods are not instances of the same function. Don't forget that the function in--ecmascript is an object, so every definition of a function is an instantiation of an object. From this perspective, it is easier to see that the each person instance contains the nature of a different function instance . To be clear, creating a function in this way causes a different scope chain and identifier resolution, but the mechanism for creating a new instance of a function is still the Same. therefore, functions with the same name on different instances are not equal, and the following code can prove this   alert (person.sayname ==person2.sayname); // false  , It is not necessary to create two function instances that accomplish the same task, and the This object does not have to bind the function to a particular object at all before executing the Code. so, by defining the function outside the constructor to solve the problem, it does solve the problem of two functions doing the same thing, but the new problem comes again: functions defined in the global scope can actually be called only on an object, which makes the global scope a bit of a misnomer. What is even more unacceptable is that if an object needs to define many methods, it is necessary to define a number of global functions, so the custom reference type is not encapsulated at All. fortunately, These problems can be solved by using prototype Mode.

    function sayname () {      alert (this. name);  }   function person (name, age) {      this. name = name;        this. age = Age ;       This. sayname = sayname;  
  • prototype mode : Each function we create has a prototype (prototype) attribute, which is a pointer to an object that is used to contain properties and methods that can be shared by all instances of a particular type. If it is understood literally, then prototype is the prototype object of the object instance created by invoking the Constructor. the advantage of using a prototype object is that you can have all object instances share the properties and methods that it contains . In other words, instead of defining the information for an object instance in the constructor, you can add that information directly to the prototype Object.

    functionperson () {} Person.prototype.name= "Nicholas"; Person.prototype.age= 29; Person.prototype.sayName=function() {alert ( this. name);}; varPerson1 =Newperson (); Person1.sayname ();//"Nicholas"varPerson2 =Newperson (); Person2.sayname ();//"Nicholas"Person1.name = "Greg"; Alert (person1.name);//"Greg"-from The exampleDeleteperson1.name; Alert (person1.name);//"Nicholas"-from the prototypeAlert (person1.sayname = = person2.sayname);//true

    In this example, the name of Person1 is masked by a new Value. however, both the access Person1.name and the access Person2.name return the values normally, namely "Greg" and "Nicholas" respectively. When accessing Person1.name in alert (), it is necessary to read its value, so it searches for a property named name on this instance, and the property does exist, so it returns its value without having to search the Prototype. When Person2.name is accessed in the same way, the property is not found on the instance, so the prototype continues to be searched, and the Name property is found There. Use the delete operator to delete person1.name, which previously saved a "Greg" value that masked the stereotype property of the same name. After deleting it, the connection to the name attribute in the prototype is Restored. therefore, when you call Person1.name again, the value of the name attribute in the prototype is Returned.

    // a simpler way to prototype patterns function person () {}   = {          "Nicholas",          +,          function() {alert (this). name);}  

  • combining constructor and prototype patterns : The most common way to create custom types is by combining the constructor pattern with the prototype Pattern. The constructor pattern is used to define instance properties, and the prototype schema 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 it shares a reference to the method, saving the memory to a minimum. In addition, this blending pattern also supports passing parameters to the constructor, which is the length of the two modes

     functionperson (name, Age) { this. Name =name;  this. Age =age ;  this. Friends = ["goser", "greg"]; } Person.prototype={constructor:person, sayname:function() {alert ( this. name);}; varPerson1 =NewPerson ("Nicholas", 29); varPerson2 =NewPerson ("Greg", 21); Person1.friends.push ("gat"); Alert (person1.friends);//"goser,greg,gat"Alert (person2.friends);//"goser,greg"Alert (person1.friends = = person2.friends);//falseAlert (person1.sayname = = person2.sayname);//true

  • Dynamic Prototyping Mode : Developers with other OO language experiences are likely to be very confused when they see independent constructors and Prototypes. The dynamic prototyping model is a formal commitment to a solution to this problem. It encapsulates all the information in the constructor, while preserving the advantages of using constructors and prototypes while initializing the prototype in the constructor (only if necessary). In other words, you can determine whether a prototype needs to be initialized by checking that a method that should exist is valid .

    functionperson (name, Age) { this. Name =name;  this. Age =age ; -----------------------------------------//      if(typeof  this. sayname! = "function") {Person.prototype.sayName=function() {alert ( this. name);      }; }  -----------------------------------------//  }  varp =NewPerson ("Nicholas", 29); P.sayname ();
  • Parasitic constructor Patterns : In general, parasitic constructor patterns can be used in situations where none of the preceding modes are Applicable. The basic idea of this pattern is to create a function that encapsulates the code that creates the object, and then returns the newly created object , but on the surface, the function is like a classic Constructor. is actually the application of the combination pattern in the design pattern .

    function person (name, age) {       varnew  Object ();        = name;        = Age ;        function () {       Alert (this. name);       };        return obj;  }   var New Person ("Nicholas");  P.sayname ();  

JavaScript Advanced Programming Study notes (5)-object-oriented programming

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.