js base - Object Oriented (constructor)

1, object-oriented: class flag, can create a plurality of objects with the same properties and methods by class
2. Create Object
1) Factory Pattern way: avoid duplication instantiated but failed to solve the identification problem
 function boss(name, age) {
          var obj = new Object();
          obj.name = name;
          obj.age = age;
          obj.run = function () {
            return "Name:" + this.name + ", Age:" + this.age + ", we are subordinate boss"
          };
          return obj;
        }
        var boss1 = new boss ( "Joe Smith", 58);
        console.log(boss1.run());
        var boss12 = new boss ( "John Doe", 58);
        console.log(boss12.run());
        console.log(typeof boss1);//object
        console.log (boss1 instanceof boss); // false, not belong boss object, difficult to distinguish
2) (a constructor argument: Avoid repeated instances of object recognition and can solve the problem)
  function Boss(name,age) {
          this.name = name;
          this.age = age;
          this.run = function () {
            return "Name:" + this.name + ", Age:" + this.age + ", we are subordinate Boss"
          };
        }
        var employee1 = new Boss ( "Joe Smith", 18); // Create Object
        console.log(employee1.run());
        var employee2 = new Boss ( "John Doe", 25);
        console.log(employee2.run());
  console.log(employee1 instanceof Boss);//true
Constructor method run () can be replaced with new Function
this.run = new Function ( "return \ 'Name: \' + this.name + \ ', Age: \' + this.age + \ ', we are subordinate Boss \'");
Constructor Features:
Creating objects 1. No display (new Object)
2. The properties and methods directly assigned to this object
3. There is no return statement
4. Examples of the function name and the name of the same construction and capital, facilitate the distinction between ordinary function
5. Create an object in the constructor must use the new operator. (transfer)
6. In the constructor body, this represents the object of this constructor declared.
 

Guess you like

Origin www.cnblogs.com/LindaBlog/p/10984187.html