JS study notes - object-oriented foundation

  Today review of js knowledge of object-oriented, knowledge in this area to do a summary.

  The first is to understand the objects and classes. Objects can be understood as a specific kind, such as a person. And people have to eat, sleep and other characteristics of the object with the same characteristics are classified, such as humans. Relationship between objects and classes that are the object of a specific class of individuals, many abstract class is an object having the same characteristics.

  Object properties and methods composition, typically in the object programming attribute performance variables, some static features, objects method of performance as a function of some dynamic features. E.g:

. 1  var ARR = [. 1, 2,. 3 ]
 2 arr.num = 4
 . 3 Console, log (arr.num) // NUM variable is the attribute of the object 4 
4  
. 5 arr.fn = function () {
 . 6    the console.log ( 4 )
 . 7  }
 . 8 arr.fn () // method 4 function fn is the object of the

  Objects can be created by new object) or form (the object literal. But this is very easy to create an object, but create more than 100 generates code redundancy, we can package up to the same code, here to introduce the factory mode and constructors in two ways.

1  // Create an object factory mode 
2  function createPerson (name) {
 . 3    var Person = new new Object ()
 . 4    PERSON.NAME = name
 . 5    person.showName = function () {
 . 6      the console.log ( the this .name)
 . 7    }
 . 8    return Person
 . 9  }
 10  
. 11  var P = createPerson ( 'pcyu' )
 12 is p.showName () // output pcyu
1  // Create object constructor embodiment 
2  function createPerson (name) {
 . 3    the this .name = name
 . 4    the this .showName = function () {
 . 5      the console.log ( the this .name)
 . 6    }
 . 7  }
 . 8  
. 9  var P = new new createPerson ( 'pcyu' )
 10 p.showName () // output pcyu

  In the constructor is the role of the new keyword when calling a new function, the function of which will point this out to create objects and the function's return value is created out of this object, in conclusion, that is, when to call a new when the function that is the constructor is called.

Guess you like

Origin www.cnblogs.com/pcyu/p/11300069.html