JS Object Oriented Essay

One: Generate instance objects from prototype objects

First build the original model for generating instance objects, and then generate instance objects based on the model of the original object.

For example, the prototype object
var item= {
    name : '';
    price : '';
  }
The simplest encapsulation, put Attributes are encapsulated in the object
   var item1={};
  item1.name = "pencil";
     item1.price = 5;// Assign values ​​according to the attributes of the prototype object

2 : Improvement of the original mode
function item(name,price) {
    return {
      name :name;
      price:price;
    }
  }
and then generating an instance object is equivalent to calling the function
var item1 = item("pencil","5");

the disadvantage of this mode is that there is no intrinsic connection between instance objects and cannot reflect It turns out that they are instances of the same prototype object

3 : The constructor is actually an ordinary function, but the this variable is used internally. By using the new operator on the constructor, an instance is created, and the this variable is bound to the instance object.

Example prototype: function item(name,price){
                   this.name=name;
                   this.price=price;  
                } 
example:var item1 = new item('pencil',5);
console.log(item1)===>output is {name:pencil,price:5}



Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327043148&siteId=291194637