JavaScript advanced day 02 note constructor and prototype inheritance ES5 added ⭐⭐ method

JavaScript advanced day 02 notes

1. Constructors and prototypes

1.1 three ways to create objects - Review

  1. Literal mode

    var obj = {};
  2. new keyword

    var obj = new Object();
  3. Constructor mode

    function Person(name,age){
      this.name = name;
      this.age = age;
    }
    var obj = new Person('zs',12);

1.2 static members and instance members

1.2.1 instance members

Instance members are members added through this inside the constructor. For example, in the following code, uname age sing is an instance member, which 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 instantiated objects

1.2.2 static members

Static members are members added to the constructor itself. For example, in the following code, sex is a static member. Static members 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.3 constructor problems

Constructor method is easy to use, but there is a problem of wasting memory.

1.4 constructor prototype

The function allocated by the constructor through the prototype is shared by all objects.

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

We can define those 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('Xue You Zhang', 19);
ldh.sing();//I can sing
zxy.sing();//I can sing

1.5 object prototype

Objects have a property __proto__ Point to constructor prototype Prototype object, the reason why we can use constructor prototype The properties and methods of the prototype object are because the object has __proto__ The existence of prototypes.
__proto__Object prototype and prototype object prototype Is equivalent
__proto__The significance of object prototype is to provide a direction or a route for the object search mechanism, but it is a non-standard attribute. Therefore, this attribute can not be used in actual development. It only points to the prototype object internally prototype

1.6 constructor

Object prototype( __proto__)And constructors( prototype)There is a property in the prototype object constructor Properties, constructor We call it a constructor because it refers back to the constructor itself.
constructor It 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 method of the object is set in the prototype object of the constructor. If there are methods of multiple objects, we can assign values to the prototype object in the form of objects, but this will overwrite the original content of the constructor prototype object, so that the modified prototype object constructor  It no longer points to the current constructor. At this point, we can add one to the modified prototype object constructor 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, such as:

 function Star(uname, age) {
     this.uname = uname;
     this.age = age;
 }
 // In many cases, we need to manually use the constructor attribute 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 can act in movies');
   }
}
var zxy = new Star('Xue You Zhang', 19);
console.log(zxy)

As a result of the above code operation, set the constructor attribute as shown in the figure:


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

1.7 prototype chain

Each instance object has another__ proto__ Property that points to the prototype object of the constructor. The prototype object of the constructor is also an object. There are also__ proto__ Attribute, so looking up layer by layer forms the prototype chain.

1.8 triangular relationship between constructor instance and prototype object

1.Constructor prototype Property points to the constructor prototype object
2.Instance objects are created by constructors,Instance object__proto__Property points to the prototype object of the constructor
3.Constructor prototype object constructor Property points to the constructor,Prototype of instance object constructor Property also points to the constructor

1.9 prototype chain and member search mechanism

Any object has a prototype object, that is, the prototype attribute. Any prototype object is also an object, and the object has__ proto__ Attributes, looking up layer by layer, form a chain, which we call prototype chain;

When accessing the properties (including methods) of an object, first find out whether the object itself has the property.
If not, find its prototype (that is __proto__directive prototype Prototype object).
If not, find the prototype of the prototype object( Object Prototype object).
And so on Object Until( null). 
__proto__The significance of object prototype is to provide a direction, or a route, for the object member search mechanism.

1.10 this point in prototype object

Both this in the constructor and this in the prototype object point to the instance object we created 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 refers to the instance object ldh

1.11 extend 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. You can always use the array sum() to calculate the data

2. Succession

2.1call()

  • call() can call a function
  • call() can modify the point of this. When using call(), parameter 1 is the modified point of this. Parameter 2, parameter 3... Use commas to separate the 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 attributes in the parent constructor

  1. Define a parent constructor first
  2. Define a 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 . Sub 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 a 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 . Sub 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;   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 the sub constructor
  Son.prototype.exam = function() {
    console.log('Children have exams');

  }
  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 the array

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

3.2 array method 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 elements
     //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 whether 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 elements
     //Parameter 3: current array
     return value < 3;
  });
console.log(flag);//false the return value is a Boolean value. As long as an element satisfying the condition is found, the loop will be terminated immediately

3.4 screening commodity cases

  1. Define array object data

    var data = [{
                id: 1,
                pname: 'millet',
                price: 3999
            }, {
                id: 2,
                pname: 'oppo',
                price: 999
            }, {
                id: 3,
                pname: 'glory',
                price: 1299
            }, {
                id: 4,
                pname: 'Huawei',
                price: 1999
            }, ];
  2. Use forEach to traverse the data and render it to the page

    data.forEach(function(value) {
      var tr = document.createElement('tr');
      tr.innerHTML = '<td>' + value.id + '</td><td>' + value.pname + '</td><td>' + value.price + '</td>';
      tbody.appendChild(tr);
     });
  3. Filter data by price

    1. Get the search button and bind the click event for it

      search_price.addEventListener('click', function() {
      });
    2. Use filter to filter out the price information entered by the user

      search_price.addEventListener('click', function() {
            var newDate = data.filter(function(value) {
              //start.value is the starting interval
              //end.value is the end interval
            	return value.price >= start.value && value.price <= end.value;
            });
            console.log(newDate);
       });
    3. Re render the filtered data to the table

      1. Encapsulate the logic of rendering data into a function

        function setDate(mydata) {
              // Clear the data in the original tbody first
          tbody.innerHTML = '';
          mydata.forEach(function(value) {
            var tr = document.createElement('tr');
            tr.innerHTML = '<td>' + value.id + '</td><td>' + value.pname + '</td><td>' + value.price + '</td>';
              tbody.appendChild(tr);
          });
         }
      2. Re render filtered data

         search_price.addEventListener('click', function() {
             var newDate = data.filter(function(value) {
             return value.price >= start.value && value.price <= end.value;
             });
             console.log(newDate);
             // Render the filtered objects to the page
             setDate(newDate);
        });
    4. Filter by product name

      1. Get the product name entered by the user

      2. Bind the click event for the query button, and filter the entered product name and this data

         search_pro.addEventListener('click', function() {
             var arr = [];
             data.some(function(value) {
               if (value.pname === product.value) {
                 // console.log(value);
                 arr.push(value);
                 return true; // return must be followed by true  
               }
             });
             // Render the data to the page
             setDate(arr);
        })

3.5 difference between some and forEach

  • If the only element in the array is queried, some method is more appropriate. If return true is encountered in some, the traversal is terminated, and the iteration efficiency is higher
  • In forEach, return will not terminate the iteration

3.6 trim method removes spaces at both ends of the string

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

3.7 get the attribute name of the object

Object. Keys (object) gets the property name in the current object, and 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.8Object.defineProperty

Object.defineProperty sets or modifies properties in an object

Object.defineProperty(Object, modified or added attribute name,{
		value:The value of the modified or added attribute,
		writable:true/false,//If the value is false, it is not allowed to modify this property value
		enumerable: false,//enumerable if the value is false, traversal is not allowed
        configurable: false  //Configurableif false, this attribute is not allowed to be deleted. Can the attribute be deleted or can the attribute be modified again
})	

Posted by rjs34 on Wed, 04 May 2022 08:48:38 +0300