JS way to create objects

An object: a package of data, a plurality of data storage container (unified management of multiple data)

  1 classification  

  1) built-in objects: Object defined by the standard ES, can be used in the implementation of any ES

     例如:Math String Number Function Object

  2) Host: Object provided by the operating environment JS

     For example: DOM BOM

  3) custom objects: user-defined

  2, consists of:

    - Properties: constituted by the attribute name (character string) and an attribute value (of any type)

    - Method: A special attribute (function value)

  3, the internal data access objects

    - Object attribute name: attribute name uncertain (variable); can not be used when the attribute names with special characters

    - Object [property name]: can be used under any circumstances

Second, the way to create objects

  1, new operator: create an empty object, and then dynamically add attributes. When the internal properties of the object initially uncertain

    Cons: Too many statements

    

  2, object literal: When you create an object suitable for internal property is determined.

    Disadvantages: When you create multiple objects, a lot of code duplication

    

 

 

   3, using the factory method: dynamic functions create objects through the factory, and the object is returned. For creating multiple objects

    Cons: There is no specific type of the object, you can not determine who is an instance of Object

    

 

 

 

   4, constructed function

    And the difference between the way the factory function: to create an object is not displayed; there is no return statement; constructor name the general needs of capital, other general lowercase; know who is an example

      (Examples of which can be seen by both Object instanceof, which is an instance of Person)

    

 

 

     The creation of objects:

      1) Create an object immediately

      2) The scope of the constructor is assigned to the new object (so this point a new object)

      3) code is performed row by row constructor

      4) The new object is returned

  Cons: If you write a function in the constructor method, then each time you create an object will instantiate a method (method is a function, the function is the object), the methods of each object

      Different. The method functions written on the outside will pollute the global namespace, and not enough privacy. This presented a prototype way to create an object

  5, the constructor prototype +

    

 

     向对象的原型中添加一些公有的属性,这样每次创建对象时就不会都重复创建。

 

  

Guess you like

Origin www.cnblogs.com/qqinhappyhappy/p/11601140.html