Objects (Object-oriented, method of creating objects, Json)

Source: Internet
Author: User

First, object-oriented
    • Process oriented: All things are pro-Pro, the specific process of each thing must know, pay attention to the process
    • Object-oriented: Looking for objects according to needs, all things are done with objects, focusing on results
    • Object-oriented features: encapsulation, inheritance, polymorphism (abstract)
    • JS is an object-based language: JS is not an object-oriented language, but it can simulate object-oriented thinking
    • An object is a definition: having characteristics and behavior, specifically referring to something
Second, the method of creating the object 1. Call the system's constructor to create an object
       varobj=NewObject ();//keyword object, uppercase initialsObj.name= "Xiao Ming"; Obj.age=20; Obj.sex= "Male"; Obj.play=function() {Console.log ("I'm playing a game.");        }; Obj.showname=function() {Console.log ("My Name" + This. Name)} Console.log (obj.name);//Xiao MingConsole.log (Obj.age);// -Console.log (Obj.sex);//maleObj.play ();//I'm playing a game .Obj.showname ();//My name is Xiaoming .

    • This method generates an object from the New keyword, and then adds properties and methods based on JavaScript's characteristics of the dynamic language to construct an object.
    • In the method of the current object, you can use this instead of the current object
    • The problem with this approach is that if we need to create objects multiple times, we need to repeat the code multiple times, which is not conducive to code reuse.

2. Factory mode: Create multiple objects at once-Factory mode create objects: Use functions to encapsulate them, and call them later
    • Original version
        functioncreatobj () {varobj=NewObject; Obj.name= "Guan Yu"; Obj.age=30; Obj.showname=function() {Console.log ("My Name" + This. Name);            }; Obj.showage=function() {Console.log ("I am this year" + This. Age);            }; returnobj; }        varobj1=creatobj (); varObj2=creatobj (); Obj1.showname ();//My name is Guan Yu .Obj1.showage ();//I'm in this year .Obj2.showname ();//My name is Guan Yu .Obj2.showage ();//I'm in this year .

This approach also implements the creation of objects, but similarly, if you need to create objects multiple times, and the property content is different, you need to repeat the code multiple times. The code reuse rate needs to be reconsidered, and the code is then modified so that it can increase the code repetition rate, and the factory method can be changed to pass in the parameter assignment.

    • Improved version
        functionCreatobj (name,age) {varobj=NewObject; Obj.name=name; Obj.age=Age ; Obj.showname=function() {Console.log ("My Name" + This. Name);            }; Obj.showage=function() {Console.log ("I am this year" + This. Age);            }; returnobj; }        varobj1= New Creatobj ("Liu Bei", 32); varobj2= New Creatobj ("Guan Yu", 30); Obj1.showname ();//My name is Liu BeiObj1.showage ();//I am this yearObj2.showname ();//My name is Guan Yu .Obj2.showage ();//I'm in this year .

Although this method can improve the reuse rate of code, there is a big flaw compared with the concept of class in object-oriented.

Object-oriented emphasizes that the properties of an object are private, but the object's methods are shared. The factory method above creates an individual private method for each object as it is created.

At the same time, because the logical same method is created for each object, memory is wasted.

    • Final version
       functionCreatobj (name,age) {varobj=NewObject; Obj.name=name; Obj.age=Age ; Obj.showname=ShowName; Obj.showage=Showage; returnobj; } showname=function() {Console.log ("My Name" + This. Name);       }; Showage=function() {Console.log ("I am this year" + This. Age);        }; varObj1=new creatobj ("Liu Bei", 32); varObj2=new creatobj ("Guan Yu", 30); Obj1.showname ();//My name is Liu BeiObj1.showage ();//I am this yearObj2.showname ();//My name is Guan Yu .Obj2.showage ();//I'm in this year .

By defining several function objects above, it solves the private problem of holding function objects for different objects. All object methods now hold references to the above two functions.

However, the object's functions and objects are independent of each other, which is incompatible with the idea of a particular method belonging to a particular class in an object-oriented manner.

3. Custom constructors Create objects (combined with first and requirement, created through Factory mode)
         functionPerson (name,age) { This. name=name;  This. age=Age ;  This. showname=function() {Console.log ("My Name" + This. Name);            };  This. showage=function() {Console.log ("I am this year" + This. Age);         };         }; varobj1=NewPerson ("Liu Bei", "32"); varObj2=NewPerson ("Guan Yu", "30"); Obj1.showname ();//My name is Liu BeiObj1.showage ();//I am this yearObj2.showname ();//My name is Guan Yu .Obj2.showage ();//I'm in this year .
    • Constructors, like factory methods, create exclusive function objects for each object. Of course, these function objects can also be defined outside the constructor, so that the object and methods are independent of each other problem.
    • The biggest problem with using constructors is that each instance will have all the properties created once. This is acceptable for numeric attributes, but it is unreasonable if each instance of a function method is created once.
    • Custom constructors: No Var, no return value, replace current object with this
    • To create a new instance of person (), you must use the new operator.
    • Differences between constructors and functions: the first letter of the constructor is generally capitalized
    • Custom constructors Create objects that do four things:
      • Open (request) space in memory to store new objects
      • Set this to a new object
      • Setting the values of properties and methods for an object
      • Return this object
4. Create objects by literal volume
      var obj={           name:"Liu Bei", age           :+,           height:"180cm"        }        Console.log (obj.name); // Liu Bei        Console.log (Obj.age); //  +        Console.log (Obj.height); // 180cm        instanceof Object); // true
    • A flaw in the literal creation of objects: disposable objects
    • Note The attribute is separated from the attribute with a comma, not a semicolon
Iii. some conclusions

1. How do I get the variable (object) that belongs to what type?

    • Syntax: The name of the variable instanceof type-------boolean type, the output is true or false
    • Type of first letter capitalized
       var obj={           name: "Zhang Fei"           ,age:32,        }        ; instanceof Object); // true

2. An object is a set of ordered properties, and the value of the property can be any type

3. Dot syntax: Nothing on the point, you can set and get and get object properties

      var obj={           name: "Liu Bei"           ,age:32,        };        Obj.height= "180cm"; // Add Height Property        Console.log (Obj.name); // Liu Bei        Console.log (Obj.age); //  +        Console.log (Obj.height); // 180cm

4. Another way to set and get Properties is through [""], which must have double quotes

       var obj={           name: "Guan Yu"           ,Age: "+",        };        obj["height"]= "190cm"; // Add Height Property        Console.log (obj["name"]); // Guan Yu        Console.log (obj["age"]); //  -        Console.log (obj["height"]); // 190cm

5.Json

      var obj={           "name": "Liu Bei"           ,"age": "+"           ,"height": "180cm"         }
    • JSON-formatted data, usually paired, in the form of key-value pairs
    • JSON is also an object in which data is enclosed in double quotes, whether it is a key or a value.
    • JSON cannot be traversed by a for loop, and can be traversed through the for......in loop

6. Data type

    • Original data type: number, String, Boolean, undefined, null, Object
    • Base type (simple type, value type): Number, String, Boolean
    • Complex Type (reference type): Object
    • Null type: Undefined, null
    • Value types are stored in the stack, reference types are stored on heaps and stacks-----objects are stored in the heap, the address of the object is stored on the stack
    • A value type passes a value, and a reference type passes an address (reference)
 //          var  obj={name:  "Li Bai" };  function   F2 (obj2) {obj2.name  = "Han Xin        "; } console.log (obj.name);  //  Li Bai          F2 (obj);  // obj2.name= "Han xin"----replaced by obj.name= "Han Xin"  Console.log (obj.name); //  Han Xin  
var num=50;         function F1 (num) {            num=60;            Console.log (num); //  -         }        F1 (num);         // num=60-----The original num=60 was replaced by NUM=50 and it's an implicit global variable        . Console.log (num); //  -
 //Example 3:        varNum1=55; varnum2=66; functionF1 (num,num1) {num=100; NUM1=100; Num2=100; Console.log (num);// -Console.log (NUM1);// -Console.log (NUM2);// -} f1 (NUM1,NUM2); //num=100;---the original num is gone. num1=55, implicit global variable        //num1=100,---The original num1. num2=66, implicit global variables        //num2=100,---Here the num2 is re-assigned to NUM2=100, the implicit global variableConsole.log (NUM1);// -Console.log (NUM2);// -Console.log (num);//Error
  //Example 4:        functionPerson (name,age,salary) { This. name=name;  This. age=Age ;  This. salary=salary; }        functionF1 (person) {Person.name= "Zhang San"; person=NewPerson ("John Doe", 18,10); }        varp=NewPerson ("Zhao Liu", 18,1000); Console.log (p.name);//Zhao LiuF1 (p); //person.name= "Zhang San"-----replaced with P.name= "Zhang San" (instead of the original "Zhao Liu")        //The following is replaced with p=new person ("John Doe", 18,10) equals a new object createdConsole.log (P.name);//Zhang San

Objects (Object-oriented, method of creating objects, Json)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.