javascript object-oriented knowledge summary

The three major characteristics of object-oriented: encapsulation, inheritance, polymorphism.

Object-oriented languages ​​have a sign, that is, the concept of a class, and through a class, you can create any number of objects with the same properties and methods to


create an object and then create new properties and methods for the object.

the first method:

   

var box=new Object();

box.name='wang';//Create a name attribute and assign a value

box.age=100;//Create an age property and assign a value

box.run=function(){
  return this.name+" "+this.age+'运用中';
}

alert(box.run());//Output the values ​​of attributes and methods
//The output result is:
//=>wang 100 is running

 

An object is created above, and its properties and methods are created. This in the run method represents the box object

itself . This is the most basic way to create objects in js, but if you need to create multiple objects, it will generate a lot of code.

In order to solve the problem of multiple similar object declarations we can use a method called "factory pattern", which is

to solve the problem of a lot of repetition of instantiated objects.

The second method:

function creatObject(name,age){ //Centralized instantiation function
  
  var obj=new Object();
  
  obj.name = name;
  
  obj.age = age;
  
  obj.run = function(){
  
    return this.name+" "+this.age+"运用中...";
  
  }
  
  return obj;

}



Call the above method to construct an instance object:

var box1 = createObject('Lee', 100);//The first instance

var box2 = createObject ('Jack',200);//The second instance

alert(box1.run());   

//The output result is:

//Lee 100 is running...

alert(box2.run());   

//The output result is:

//Jack 200 is running...

Use the constructor method to build the corresponding object:
function Box(name,age){//Constructor mode

  this.name=name;

  this.age=age;
  this.run=function(){

    return this.name+this.age+"运用中"

  };

};

var box1=new Box("Lee","100");

var box2=new Box("Jack","200");

alert(box1.run);
// The output result is:
//=>Lee100 in use
alert(box1 instanceof Box);
//The output result is:
//=>true
//Indicates that box1 belongs to Box

The difference between the method using the constructor and the method using the factory pattern is as follows:

1. The constructor method does not show the creation of the object (new Object());
2. Assign properties and methods directly to this object;
3. There is no return statement.
The constructor's method has some specifications:
1. The function name and the instantiation constructor name are the same and capitalized, (PS: not mandatory, but writing this way helps to distinguish the constructor from the
normal function);
2. To create an object through the constructor, the new operator must be used.




 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326122436&siteId=291194637