JS === object-oriented summary

Create Object

1. factory pattern

  function createPerson(name,age,job){

    var o = new Object();

    o.name = name;

    o.age = age;

    o.job = jobs;

    o.sayName = function(){

    alert(this.name);

  };

  return o;

  }

 

var person1 = createPerson("Emily",21,"software Engineer") ;

While using the factory pattern to solve similar objects created much of the problem, but it does not solve the problem of object recognition (that is, how do I know the type of an object)

 

2. Constructor mode

  function Person(name,age,job){

    this.name = name;

    this.age = age;

    this.job = job;

    this.sayName = function(){

      alert(this.name);

    };

  }

var person1 = new Person("Emily",22,"software engineer");

1. Create an object does not display

2. The directly assigned to the properties and methods of this object

3. There is no return statement

In this way, call the constructor will actually go through the following four steps:

1) create a new object;

2) The scope of the constructor assigns a new object (this points to the new object);

3) execution code constructor

4) returns a new object

Disadvantages:

Each instance has a method, but these methods are not the same instance of a function. Functions are also objects, each defining a function, which is an object instantiated.

 

3. prototype model

  function Person(){

}

  Person.prototype.name = "Emily";

  Person.prototype.age = 20;

  Person.prototype.job = "SoftWare Engineer";

  Person.prototype.sayName = function(){

    alert(this.name);

};

  was PERSON1 = new Person ();

Properties and methods, are placed in the prototype, the prototype model: shared properties.

When you create an instance of time, you will be able to access the properties and methods of the prototype, and the instance If you modify the properties and methods of the prototype will also affect other instances.

 

4. The combination of model and prototype model constructor

  function Person(name,age,job){

    this.name = name;

    this.age = age;

    this.job = job;

}

  Person.prototype = {

  constructor : Person;

  sayName : function(){

    alert(this.name);

  }

}

 

var person = new Person("Emily" , 22,"Software Engineer")

 

  Instance constructor defined attributes, properties and methods defined in common prototype.

Guess you like

Origin www.cnblogs.com/rabbit-lin0903/p/11229110.html