Early to overeating, noon eat tide, late to eat every day is eat! Eat spit bubbles made!, eat every day, also not fat who find this reason to ah, although recently eat less frequency, but really had several environment nice and delicious, mainly I can find their own strength is not allowed, bosses are different, not to have, one shot is overeating, ha ha ha ha ha. Recently is wood empty time anyway also have to write, because I feel I really bad, js for native understand really shallow, so feel touched the core, then can not but always want to touch the core of content, need to digest, if can’t digest always feel what is not completed, the feeling is very bad to eat not sweet, sleep not sweet, Do what what is not fragrant, ha ha ha ha ha anyway master is very fragrant ah.

1. Understand the object

  • The constructor
      var person = new Object(a); person.name ="Nichplas" ;
      person.age = 29;
      person.job  = ""Software Engineer"; person.sayName = function (){ alert(this.name); }Copy the code
  • Word variable syntax
    var person = {
        name: "Nichplas".age:29.job:"Software Engineer".sayName:function(){
            alert(this.name); }}Copy the code

2. Attribute categories

  • Data attributes

A data attribute contains the value location of a data. Values can be read and written from this location. A data attribute provides four different features that represent the behavior of the [[64x]] system. The property can be deleted through delete and redefined, the property can be modified, and the property can be modified as an accessor property. – [[Enumerable]]: Returns a property through a for-in loop. – [[Writable]]: indicates the Value of an attribute that can be modified. – [[Value]]: indicates the data Value containing this attribute. When reading property values, read from this position; When writing property values, store the new values in this location. The default is undefined. Object.defineproperty () takes three arguments

   // object.defineProperty (attribute Object, attribute name,{})
   // The property of the trailing object is different, enumerable, writable, and Value, which sets one or more values
   var person = {};
   Object.definePeoperty(person,"name", {writable:false.value:"Nicholas"
   });
   alert(person.name); // Nicholas
   person.name = "lihua";
   alert(person.name); // Nicholas
Copy the code
  • Accessor properties

Accessing its properties does not contain property values; They contain a getter and setter function (not required) for Vue’s data response, which uses getter and setter functions and calls the getter function to return a valid value when reading accessor properties; When writing accessor properties, [[Get]], a new setter function, signals without any additional control system, and passes in a new value — [[64X]], signals without any additional control system. The default is undpay. – [[Set]]: The function called on writing the properties, Object.defineProperty(), defines the accessor properties

var book = {
    _year :2020.edition:1
}
Object.defineProperty(book,"year", {get:function(){
        return this._year;
    },
    set:function(newValue){
        if(newValue>2020) {this._year = newValue;
            this.edition + = newValue -2020;
        }
    }
})
book.year =2022; // Trigger the set method
alert(book.edition) // Trigger get method 3
Copy the code
  • Defining multiple properties

Object.defineproperties (), which takes two arguments: the first is the Object to which attributes are added and modified, and the second is a one-to-one correspondence between the attributes of the Object and the attributes to be added or modified in the first Object

var book = {};
Object.defineProperties(book,{
    _year: {writable:true.value:2020
    },
    edition: {writable:true.value:1
    },
    year: {get:function(){
            return this._year
        },
        set:function(){
            if(newValue>2020) {this._year =newValue;
                this.edition+ =  newValue -2020; }}}})Copy the code
  • Read property features

Object. GetOwnPropertyDescriptor (), takes two parameters: the first is: attributes of objects and to read the names of the descriptor

var descriptor = Object.getOwnPropertyDescriptor(book,"_year");
alert(descriptor.value) ;  / / 2020
alert(descriptor.configurable) ; //false
Copy the code

3. Create an object

Using word variables or new objects can create objects, but there are obvious disadvantages. Using the same excuse to create many objects can lead to a lot of repetitive code

  • Factory pattern: to achieve the same thing the same code into the same function, to achieve the function as long as the execution of this function, this is the factory pattern, also called “encapsulation” function, which is “low coupling, high cohesion”, so as to reduce the redundant code page, improve the utilization ratio of code duplication.
```javascript function createPerson(name,age){ var person =new Object(); Person.name = name; // Create a new object. person.age = age; Person.showname = function(){console.log(" name: "+this.name); } person. ShowAge = function(){console.log(" age: "+this.age); } // return person; } var p1 = createPerson(" createPerson ",45); Var p2 = createPerson(" createPerson ",20); p1.showName(); p2.showName(); console.log(p1.showName==p2.showName); //false ```Copy the code

Disadvantages: Normally objects are created by new, such as new Date(), instead of method creation. (var p1=createPerson(” user “,45)) Using new to create a person simplifies some of the code and also introduces some new features. Each object has its own set of methods that waste resources console.log(p1.showname == p2.showname); If function() is created using new function(), a new function object will be created, resulting in a waste of resources.

  • All arrays are instances of the built-in Array class. All objects are instances of the built-in Array class. Functions are instances of the built-in Object class.
    • Constructor notation
      function CreatePerson (name,age){  // The constructor begins with a capital letter
          this.name =name;
          this.age = age;
          this.showName = function (){
              console.log("Name:"+ this.name); };this.showAge = function (){
              console.log("Name:"+this.age);
          }
          // Do not return the object!!
      }
    
      var p1 = new CreatePerson("Zhang".45);
      var p2 = new CreatePerson("Bill".20);
      p1.showName();
      p2.showName();
      console.log(p1.showName==p2.showName); //false
      console.log(p1.constructor == CreatePerson) // true
      console.log(p2.constructor == CreatePerson) // true
      //1. We see that the new method is used to create the object.
      / / 2. But the console. The log (p1) showName = = p2) showName); // If false is still false, there is still a waste of resources.
    Copy the code
    • Treat constructors as objects

    The only difference between constructors and other functions is the way they are called. But constructors are functions, and there is no special syntax for defining constructors.

    // constructor
    var person =new CreatePerson("Nicholas".29);
    person.showName();
    // as a normal function
    CreatePerson("Greg".27);
    window.showName();
    // call in the scope of another object
    var o = new Object(a); Person.call(o,"kasare".25);
    o.showName();
    Copy the code
    • Constructor problem

    Constructors are useful but not without their drawbacks. The main problem with using constructors is that each method has to be recreated on each instance. There’s really no need to create two instances of Function that do the same thing; And with this, there’s no need to bind the function object to a particular object before executing the code

    function Person(name,age){
        this.name = name;
        this.age= age;
        this.showName = showName;
    }
    funtion showName(){
        alert(this.name);
    }
    Copy the code

    Thus, since showName contains Pointers to only functions, instance objects share the same showName function in the global scope, but there is a new problem. Functions in the global scope can only be called by one object, which is a bit less elegant in the global scope, and if there are many methods, That requires defining many methods in the global scope. So there’s a better way to do it

  • The prototype pattern javascript dictates that each function has a prototype property, which is a pointer to an object whose purpose is to contain properties and methods that can be shared by all instances of a particular type. That is, prototype is the prototype object of the object instance created by calling the constructor. I don’t know what it is hahaha look at the code
    • Make up for the shortcomings of constructors

         function Person(){
      
         }
         Person.prototype.name = "Nicholas";
         Person.prototype.age = 29;
         Person.prototype.sayName =function(){
             alert(this.name);
         }
         var person1 = new Person();
         person1.sayName();  // "Nicholas"
         var person2 = new Person();
         person2.sayName();  // "Nicholas"
         alert(person1.sayName == person2.sayName); // true
      Copy the code
    • Understanding prototype objects

      1. Whenever a new function is created, a Prototype property is created for that function according to a specific set of rules, which points to the function’s prototype object. All the prototype object will automatically receive a constructor (pointing to the constructor) properties, and then take in front of the chestnut for Person. The prototype. The constructor to the Person.

      Whenever you create an instance by calling the constructor, the instance will contain a pointer (an inner property) to the constructor’s prototype object. This pointer is called [[Prototype]] (protp). The most important thing to make clear is that the link exists between the instance and the constructor’s prototype object. Let’s look at a diagram2. IsPrototypeOf ():[[Prototype]] :[prototypeof ():[[Prototype]]javascript Person.prototype.isPrototypeof(person1); // true Person.prototype.isPrototypeof(person2); // true GetPrototypeOf (): Object.getProtoTypeof () returns the value of [[Prototype]]. 4. How to search for an attribute: First, start from the instance itself. If an attribute with a given name is found in the instance, the value of the attribute is returned; Not found proceed to the next step then: Continue searching for the prototype object to which the pointer points, looking for the property with the given name in the prototype object. If the property is found in the stereotype object, the value of the property is returned. 5. HasOwnProperty (): Checks whether a property exists in the instance or in the prototype, and returns true only if the given property exists in the object instance.javascript function Person(){}; Person.prototype.name = "Nicholas"; Person.prototype.age = 29; Person.prototype.sayName =function(){ alert(this.name); } var person1 = new Person(); var person2 = new Person(); alert(person1.hasOwnProperty("name")) // false person1.name ="Greg" console.log(person1.name); alert(person1.hasOwnProperty("name")) //true Since hasOwnProperty() returns true only if it exists in the instance, but false if it does not exist or if it exists in the prototype. The in operator understands your problem, and the in operator determines that the property returns true in both instances and prototypes.Function hasPrototypeProperty (object,name){return! object.hasOwnProperty(name)&&(name in object) }7.object.keys (): This method takes an Object as an argument and returns an array of strings containing all the enumerable attributes.

      }
      Person.prototype.name = "Nicholas";
      Person.prototype.age = 29;
      Person.prototype.sayName =function(){
          alert(this.name);
      }
      var keys = Object.keys(Person.prototype);
      alert(keys);  // "name,age,job,sayName"
      var person1 = new Person();
      person1.name = "Rob";
      person1.age = 31;
      var p1keys =Object.keys(person1);
      alert(p1keys);  // "name,age"
      ```
      Copy the code
      1. For simpler prototype syntax, you may have noticed that in the previous example, you need totype Person.prototype every time you add an attribute. There must be an easier way to write it, but notice that person. prototype equals a new object. The result is that constructor no longer points to Person, essentially overwriting the default Prototype object. If constructor is important, set it manually.
        function Person(){};
        Person.prototype ={
            constructor:Person, // Set it manually
            name:"Nicholas".age:29.sayName:function(){
                alert(this.name); }}Copy the code
      2. Because the search process in the prototype is one search at a time, what we change in the prototype immediately shows up in the instance — even if we change the prototype after the instance is created
        var friend = new Person();
        Person.prototype.sayHi=function(){
            alert("hi");
        }
        friend.sayHi();  // "hi" will not return an error
        Copy the code

        While you can always add properties and methods to a Prototype, overriding a Prototype object is different. When we call the construct function, we add a [[Prototype]] pointer to the original Prototype to the instance. If we change the Prototype completely, we break the link

      3. A prototype of a native object
      Native reference types (Object, Array, String...) Both define methods on a prototype of their constructors. For example, array. prototype can be found in the sort method (all methods we call directly now are actually written in the prototype object);Copy the code
      1. There are also problems with prototype objects
      If you look at our constructor, you can pass parameters in functions, but you can't pass parameters in prototype objects. The second major problem is that attributes in stereotypes are shared by many instances, which is fine for functions, but more problematic for attributes that contain reference type values. The following example is what if I want to have all of my properties? ```javascript function Person(){}; Person.prototype ={ constructor:Person, name:"Nicholas", age:29, friends:["Shelby","Count"], sayName:function(){ alert(this.name); } } var person1 = new Person(); var person2 = new Person(); person1.friends.push("Van"); alert(person1.friends); // "Shelby,Count,Van" alert(person2.friends); // "Shelby,Count,Van" ```Copy the code
  • Combining the constructor pattern with the stereotype pattern solves the problem of using the stereotype pattern alone, resulting in shared properties that cannot have their own copy of instance properties
      function Person(name,age){
          this.name = name;
          this.age= age; // The attributes that you want to have unique are all inside the constructor
          this.showName = showName;
      }
      Person.prototype ={
          constructor:Person, 
          sayName:function(){
              alert(this.name); }}var person1 = new Person();
      var person2 = new Person();
      person1.friends.push("Van");
      alert(person1.friends); // "Shelby,Count,Van"
      alert(person2.friends); // "Shelby,Count"
    Copy the code
  • Dynamic prototype model dynamic prototype is dedicated to all the information inside the package in the constructor, and through the constructor initializes the prototype, and maintain the advantages of using the constructor and the prototype at the same time, in other words, can check a whether there should be a method effectively, to decide whether to need to initialize the prototype.
    function (name,age){
      this.name = name;
      this.age= age; 
      if(typeof this.sayName! ="function"){
          Person.prototype.sayName = function(){
              alert(this.name); }}}Copy the code
  • The basic idea of the parasitic constructor pattern is to create a function that simply encapsulates the code that created the object and then returns the newly created object. On the surface, however, this function looks like a typical constructor. Here’s an example. This pattern is exactly the same as the factory pattern, except that we use the new operator and call the wrapper function we use a constructor
      function Person(name, age, job){
          var o = new Object(a); o.name = name; o.age = age; o.job = job; o.sayName =function(){
              alert(this.name);
          };    
          return o;
      }
      
      var friend = new Person("Nicholas".29."Software Engineer");
      friend.sayName();  //"Nicholas"
    Copy the code

    This pattern can be used in special cases to create constructors for objects. Suppose we want to create a special array with extra methods. Because you cannot modify the Array constructor directly, you can use this pattern.

      function SpecialArray(){
          // Create an array
          var values = new Array(a);/ / add value
          values.push.apply(values, arguments);
      
          // Add method
          values.toPipedString = function(){
              return this.join("|");
          };
      
          // Return an array
          return values;
      }
      var colors = new SpecialArray("red"."blue"."green");
      alert(colors.toPipedString()); //"red|blue|green"
    Copy the code
  • Before you look at the secure constructor pattern, look at the concept of a secure object. A secure object is an object that has no public attributes and that other methods do not refer to this. Secure objects are best used in secure environments where the use of this and new is prohibited, or to prevent data from being altered by other applications. The secure constructor follows a similar pattern to the parasitic constructor, except that the newly created object instance method does not reference this. The second is to call the constructor without using the new operator. Such as:
    function Persion(name, age, job) {
      // Create the object to return
      var o = new Object(a);// Add method
      o.sayName = function() {
          alert(name);
      }
      return o;
    }
    var p1 = Persion('bill'.23.'FE');
    p1.sayName() // bill;
    Copy the code

    The code variable p1 above holds a secure object, and there is no way to access other data members other than by calling sayName().