06 constructors and prototypes

1. Constructors and prototypes

1.1 three creation methods of objects

  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, and instance members can only be accessed through instantiated objects

 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 – solve the problem of wasting memory

We want all objects to use the same function, which saves memory. What should we do?

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, and all properties and methods of this object will be owned by the constructor.

What is the prototype?

An object, we call prototype object

What is the role of the prototype?

Sharing method

We can define those invariant methods directly on the prototype object, so that all object instances 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__ proto__

Every object has an attribute proto that points to the prototype object of the constructor. The reason why we can use the properties and methods of the prototype object of the constructor is because the object has a proto prototype.
__ proto__ Object prototype and prototype object prototype are equivalent
The significance of proto 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 prototype internally

1.6 constructor

Both proto and prototype objects have a property constructor. 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 the object are 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 contents of the constructor prototype object, so that 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, 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 play movies');
   }
}
var zxy = new Star('Xue You Zhang', 19);
console.log(zxy)

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__ 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.Of the prototype object of the constructor constructor Property points to a 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 an object's properties (including methods), 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 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

Note: array and string built-in objects cannot override the operation Array.prototype = {} for prototype objects, but only Array.prototype.xxx = function() {}

 Array.prototype.sum = function() {
   var sum = 0;
   for (var i = 0; i < this.length; i++) {
   		sum += this[i];
   }
   return sum;
 };
 //At this time, the sum() method already exists in the array object. You can use the array. sum() to sum 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 properties 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 child inherits the properties of 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; there will be problems with direct assignment. 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('The child wants an exam');

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

3.ES5 new method

3.1 array method forEach traversal array

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

var arr = [1, 2, 3];
var sum = 0;
arr.forEach(function(value, index, array) {
    console.log('Each array element' + value);
    console.log('Index number of each array element' + index);
    console.log('Array itself' + array);
    sum += value;
})
console.log(sum);

3.2 array filtering 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 is the 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 is the 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 the 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 start 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 property name,{
		value:The value of the modified or added property,
		writable:true/false,//If the value is false, this property value is not allowed to be modified
		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
})	

Keywords: Javascript html5 html

Added by tomdude48 on Sun, 10 Oct 2021 15:50:59 +0300