2: The magic of constructors

Objectives:

Be able to figure out the constructor and prototype

Understanding inheritance of constructors

Master some new methods of es5

1. Constructors and prototypes

1.1 general

In a typical OOP language (such as Java), there is the concept of class. Class is the template of object, and object is the instance of class. But before ES6,
The concept of introducing classes is not used in JS.
ES6, full name ECMAScript 6.02015.06 release. But at present, the JavaScript of browser is ES5 version, and most of the higher versions browse
The browser also supports ES6, but only implements some features and functions of ES6.
Before ES6, objects were not created based on classes, but defined objects and their characteristics with a special function called a build function.
There are three ways to create an object:

  1. Object Literal
  2. new Object()
  3. Custom constructor

1.2 constructor

Constructor is a special function, which is mainly used to initialize objects, that is, to assign initial values to object member variables. It is always used with new. I
You can extract some common properties and methods from the object, and then encapsulate them into this function. In JS, you should pay attention to the following two points when using the constructor:

  1. Constructor is used to create an object of a certain type, with the initial uppercase
  2. Constructors need to be used with new to make sense
  3. New does four things when it executes: ① create a new empty object in memory. ② Let this point to this new object. ③ Execute the code in the constructor to add properties and methods to the new object. ④ Return the new object (so return is not required in the constructor).

1.3 three ways to create objects - Review

  1. Literal measure
   var obj = {};
  1. new keyword
   var obj = new Object();
  1. Constructor method
  function Person(name,age){
     this.name = name;
     this.age = age;
   }
   var obj = new Person('zs',12);

1.4 static members and instance members

1.4.1 instance members

The instance member is the member added through this inside the constructor. For example, uname age sing in the following code is the instance member. The instance member can only be accessed through the instantiated object

 function Star(uname, age) {
     this.uname = uname;
     this.age = age;
     this.sing = function() {
     console.log('I can sing');
    }
}
var ldh = new Star('Lau Andy', 18);
console.log(ldh.uname);//Instance members can only be accessed through instanced objects

1.4.2 static members

Static member the member added to the constructor itself. For example, in the following code, sex is a static member, which can only be accessed through the constructor

 function Star(uname, age) {
     this.uname = uname;
     this.age = age;
     this.sing = function() {
     console.log('I can sing');
    }
}
Star.sex = 'male';
var ldh = new Star('Lau Andy', 18);
console.log(Star.sex);//Static members can only be accessed through constructors

1.5 problems with constructors

The constructor method is easy to use, but there is a waste of memory.

1.6 prototype of constructor

The functions assigned by the constructor through the prototype are shared by all objects.

JavaScript specifies that each constructor has a prototype property that points to another object. Note that this prototype is an object. All the properties and methods of this object will be owned by the constructor.

We can define the invariant methods directly on the prototype object, so that all instances of the object can share these methods.

function Star(uname, age) {
    this.uname = uname;
    this.age = age;
}
Star.prototype.sing = function() {
	console.log('I can sing');
}
var ldh = new Star('Lau Andy', 18);
var zxy = new Star('Zhang Xueyou', 19);
ldh.sing();//I can sing
zxy.sing();//I can sing

1.7 object prototype

Object will have a property__ proto__  The prototype object pointing to the constructor. The reason why our object can use the properties and methods of the prototype object of the constructor is that the object has__ proto__  The existence of archetypes.
Wei proto__ Object prototype and prototype object are equivalent
 Wei proto__ The meaning of object prototype is to provide a direction, or a route, for the object search mechanism, but it is a non-standard attribute, so in actual development, this attribute can not be used, it only points to prototype object internally

 function Star(name, age) {
            this.name = name;
            this.age = age;
        };
        Star.prototype.sing = function() {
            console.log('i can song')
        }

        var ldh = new Star();
        console.log(ldh.__proto__ == Star.prototype) // true

1.8 constructor

Object prototype (__ proto__) There is a property constructor in the prototype object of constructor and prototype. Constructor is called constructor because it refers to the constructor itself.
Constructor is mainly used to record which constructor the object refers to. It can make the prototype object point to the original constructor again.
In general, the methods of an object are set in the prototype object of the constructor. If there are multiple object methods, we can assign the prototype object as an object, but this will overwrite the original content of the constructor prototype object, so the modified prototype object constructor will no longer point to the current constructor. At this point, we can add a constructor to the modified prototype object to point to the original constructor.

If we modify the original prototype object and assign an object to the prototype object, we must manually use the constructor to refer back to the original constructor as follows:

 function Star(uname, age) {
     this.uname = uname;
     this.age = age;
 }
 // In many cases, we need to manually use the constructor property to refer back to the original constructor
 Star.prototype = {
 // If we modify the original prototype object and assign an object to the prototype object, we must manually use the constructor to refer back to the original constructor
   constructor: Star, // Manually set the pointer back to the original constructor
   sing: function() {
     console.log('I can sing');
   },
   movie: function() {
     console.log('I'll make a movie');
   }
}
var zxy = new Star('Zhang Xueyou', 19);
console.log(zxy)

For the above code running result, set constructor property as shown in the figure:

If the constructor property is not set, as shown in the figure:

1.9 prototype chain

Each instance object has another__ proto__ Property refers to the prototype object of the constructor. The prototype object of the constructor is also an object__ proto__ Attribute, so that layer by layer looking up to form a prototype chain.

1.10 triangle relationship between constructor instance and prototype object

1. The prototype property of the constructor points to the prototype object of the constructor
2. The instance object is created by the constructor. The__ proto__ Property points to the prototype object of the constructor
3. The constructor property of the prototype object of the constructor points to the constructor, and the constructor property of the prototype object of the instance object also points to the constructor

1.11 prototype chain and member search mechanism

Any object has a prototype object, that is, a prototype property. Any prototype object is also an object, and the object has__ proto__ Attribute, such a layer to look up, it forms a chain, we call this prototype chain;

When accessing the properties (including methods) of an object, first find whether the object itself has the property.
If not, look for its prototype (that is__ proto__ The prototype object pointed to).
If not, find the prototype of the prototype Object.
And so on until the Object is found (null).
Wei proto__ The meaning of object prototype is to provide a direction, or a route, for object member searching mechanism.

1.12 this point in prototype object

Both this in the constructor and this in the prototype object point to the instance object that we get from new

function Star(uname, age) {
    this.uname = uname;
    this.age = age;
}
var that;
Star.prototype.sing = function() {
    console.log('I can sing');
    that = this;
}
var ldh = new Star('Lau Andy', 18);
// 1. In the constructor, this refers to the object instance ldh
console.log(that === ldh);//true
// 2. this in the prototype object function points to the instance object ldh

1.13 extending built-in methods for arrays through prototypes

Array.prototype.sum = function() {
   var sum = 0;
   for (var i = 0; i < this.length; i++) {
   sum += this[i];
   }
   return sum;
 };
 //At this point, the sum() method already exists in the array object. sum() can always be used to find data

2. Inheritance

2.1 call()

  • call() can call a function
  • call() can change the point of this. When using call(), the first parameter is the modified point of this, parameter 2, parameter 3 Comma separated connection
 function fn(x, y) {
     console.log(this);
     console.log(x + y);
}
  var o = {
  	name: 'andy'
  };
  fn.call(o, 1, 2);//When the function is called, this points to the object o,

2.2 the child constructor inherits the properties in the parent constructor

  1. Define a parent constructor first
  2. Define another sub constructor
  3. The child constructor inherits the properties of the parent constructor (using the call method)
 // 1. Parent constructor
 function Father(uname, age) {
   // this points to the object instance of the parent constructor
   this.uname = uname;
   this.age = age;
 }
  // 2. Child constructor 
function Son(uname, age, score) {
  // this points to the object instance of the child constructor
  3.use call Method to implement the property of the child inheriting the parent
  Father.call(this, uname, age);
  this.score = score;
}
var son = new Son('Lau Andy', 18, 100);
console.log(son);

2.3 borrowing prototype object inheritance method

  1. Define a parent constructor first
  2. Define another sub constructor
  3. The child constructor inherits the properties of the parent constructor (using the call method)
// 1. Parent constructor
function Father(uname, age) {
  // this points to the object instance of the parent constructor
  this.uname = uname;
  this.age = age;
}
Father.prototype.money = function() {
  console.log(100000);
 };
 // 2. Child constructor 
  function Son(uname, age, score) {
      // this points to the object instance of the child constructor
      Father.call(this, uname, age);
      this.score = score;
  }
// Son.prototype = Father.prototype ; in this way, the direct assignment will be problematic. If the child prototype object is modified, the parent prototype object will change with it
  Son.prototype = new Father();
  // If you modify the prototype object in the form of an object, don't forget to use the constructor to refer back to the original constructor
  Son.prototype.constructor = Son;
  // This is a special method of sub constructor
  Son.prototype.exam = function() {
    console.log('A child needs an exam');

  }
  var son = new Son('Lau Andy', 18, 100);
  console.log(son);

The result of the above code is shown in the figure:

3.ES5 new method

3.1 array method forEach traverses array

 arr.forEach(function(value, index, array) {
       //Parameter 1: array element
       //Parameter 2: index of array element
       //Parameter 3: current array
 })
  //for loop equivalent to array traversal has no return value

3.2 array method filter filter array

 var arr = [12, 66, 4, 88, 3, 7];
  var newArr = arr.filter(function(value, index,array) {
  	 //Parameter 1: array element
     //Parameter 2: index of array element
     //Parameter 3: current array
     return value >= 20;
  });
  console.log(newArr);//[66,88] / / the return value is a new array

3.3 array method some

some Find if there are elements in the array that meet the conditions 
 var arr = [10, 30, 4];
 var flag = arr.some(function(value,index,array) {
    //Parameter 1: array element
     //Parameter 2: index of array element
     //Parameter 3: current array
     return value < 3;
  });
console.log(flag);//The return value of false is a Boolean value. As long as one element satisfying the condition is found, the loop will be terminated immediately

3.4 screening cases

Effect preview:

Case study:

  1. Define array object data

  2. Use forEach to traverse the data and render it to the page

  3. Filter data by price

  4. Filter by product name

  5. Re render after each filter (delete last rendered result)

Example code:

<script>
        // Define data
        var arr = [{
            id: 001,
            type: 'Rifle',
            name: 'M4A1',
            range: 1000
        }, {
            id: 002,
            type: 'Rifle',
            name: 'AKM',
            range: 800
        }, {
            id: 003,
            type: 'Rifle',
            name: 'M762',
            range: 800
        }, {
            id: 004,
            type: 'Submachine gun',
            name: 'uzi',
            range: 500
        }, {
            id: 005,
            type: 'machine gun',
            name: 'M649',
            range: 500
        }, {
            id: 006,
            type: 'Single shot sniper',
            name: 'AWM',
            range: 1500
        }];
        // Get element
        var tbody = document.querySelector('tbody');
        var low = document.querySelector('#low');
        var high = document.querySelector('#high');
        var myType = document.querySelector('#my-type');
        var btn = document.querySelector('button');

        // Load page rendering
        render(arr);

        // Render data (encapsulate function reuse)
        // Create tr and td
        function render(myarr) {
            tbody.innerHTML = '';
            myarr.forEach(function(value, index) {
                // Create element
                var tr = document.createElement('tr');
                tr.innerHTML = '<td>' + value.id + '</td><td>' + value.type + '</td><td>' + value.name + '</td><td>' + value.range + '</td>'
                tbody.appendChild(tr);
            });
        };

        // Click btn button or lose focus when inputting the farthest distance, and refresh the data
        high.addEventListener('keyup', function(e) {
            var newArr = arr.filter(function(value) {
                return value.range >= low.value && value.range <= high.value
            });
            if (e.keyCode == 13) {
                render(newArr);
                low.value = '';
                high.value = '';
            }
        });

        // After inputting the type of search, click btn button or lose focus, and refresh the data
        myType.addEventListener('keyup', function(e) {
            if (e.keyCode == 13) {
                btn.click();
            }
        });

        btn.addEventListener('click', function() {
            var newArr = arr.filter(function(value) {
                return value.type == myType.value.trim()
            });
            render(newArr);
            myType.value = '';
        });
    </script>

3.5 difference between some and forEach

  • If you want to query the only element in an array, it is more appropriate to use some method. If you encounter return true in some, you will be more efficient to terminate the iteration
  • return does not terminate iteration in forEach

3.6 trim method to remove spaces at both ends of string

var str = '   hello   '
console.log(str.trim())  //hello, remove space at both ends
var str1 = '   he l l o   '
console.log(str.trim())  //he l l o remove space at both ends

3.7 get the property name of the object

Object.keys Gets the property name in the current object. The return value is an array

 var obj = {
     id: 1,
     pname: 'millet',
     price: 1999,
     num: 2000
};
var result = Object.keys(obj)
console.log(result)//[id,pname,price,num]

3.8 Object.defineProperty

Object.defineProperty Set or modify properties in objects

Object.defineProperty(Object, modified or added property name,{
		value:Value of modified or added property,
		writable:true/false,//If the value is false, the property value cannot be modified
		enumerable: false,//enumerable traversal not allowed if value is false
        configurable: false  //If configured is false, it is not allowed to delete whether the property can be deleted or whether the property can be modified again
})	

Come on baby

Tags: Attribute Javascript Java ECMAScript

Posted on Sun, 07 Jun 2020 00:28:03 -0700 by jmgarde