Learning the front end (37) ~ js learning (XIV): creating an object

Create a custom object in several ways

One way: object literal

The object is a literal {} . Inside the properties and methods are key-value pairs :

  • Button: attribute name.

  • Found: equivalent property value, may be any type of values ​​(numbers, strings, Boolean type, function type, etc.).

E.g:

There he = {
            name: "No. One eternal"
            age: 26,
            isBoy: true,
            sayHi: function() {
                console.log(this.name);
            }
        };

console.log (d);

Console output:

 

 

 

Second way: the factory pattern

Large quantities of objects created by this method.

    /*
        * Create an object using the factory method
        * You can create objects in large quantities by this method
        */
    function createPerson(name, age, gender) {
        // Create a new object
        var obj = new Object();
        // add properties to objects in
        obj.name = name;
        obj.age = age;
        obj.gender = gender;
        obj.sayName = function() {
            alert(this.name);
        };
        // return the new object
        return obj;
    }

    var obj2 = createPerson ( "pig" 28, "M");
    var obj3 = createPerson ( "Skeleton Demon" 16, "F");
    var obj4 = createPerson ( "spider" 18, "F");

The first time you see this factory model, you may feel strange. If you simplify it, this can be written in the following form, which is easier to understand :(, create objects using the new Object)

var obj = new Obect ();
obj.name = 'pig';
obj.age = 28;
obj.gender = 'man';
obj.sayHi = function() {
    alert('hello world');
};

Drawbacks:

Creating an object using the factory method, constructor is Object . So the object is created Object of this type , has led us unable to distinguish between a variety of different types of objects.

Three ways: using a constructor

        // constructor using custom object
        var stu1 = new Student("smyh");
        console.log(stu1);
        stu1sayHi ();

        var stu2 = new Student("vae");
        console.log(stu2);
        stu2.sayHi ();


        // create a constructor
        function Student(name) {
            this.name = name; // this refers to the current object instance Important]
            this.sayHi = function () {
                console.log (this.name + "much");
            }
        }

Print Results:

 

 

 Next, we specifically speaking about the constructor.

Constructor

Code introduced

      // create a constructor, designed to create a Person object
      function Person(name, age, gender) {
        this.name = name;
        this.age = age;
        this.gender = gender;
        this.sayName = function() {
          alert(this.name);
        };
      }

      var per = new Person ( "Monkey", 18, "M");
      var per2 = new Person ( "rabbit fine" 16, "F");
      var per3 = new Person ( "rush Pa" 38, "M");

      // create a constructor, designed to create a Dog object
      function Dog() {}

      var dog = new Dog();

The concept constructor

Constructor: A special function is mainly used to create and initialize the object, which is assigned an initial value for the member variable objects. It  new use only makes sense together.

We can put some public object properties and methods extracted, and then encapsulated inside the constructor.

The difference between the constructor and general functions

Way to create a constructor function and the general is no different, except that the constructor's first letter capitalized habit .

The difference between a constructor and a normal function is to call different ways: an ordinary function is called directly, while the constructor need to use the new keyword to call.

this point is also different:

  • 1. in the form of a function call, this is always a window. For example, fun();the equivalent ofwindow.fun();

  • 2. call the form of a method, this method is that the object calls

  • 3 . When you call the constructor of the form, this is an instance of the newly created object

New execution flow of a constructor

new When executed, this will do the following four things:

(1) open up memory space, create a new empty object in memory.

(2) to make this point to the new object.

(3) the code inside the constructor is executed, the new object to add properties and methods.

(4) returns the new object (so inside the constructor does not need to return).

Because this means that a new object instance after Object. Thus, the following code:

        // Create a function
        function createStudent(name) {
            var student = new Object();
            student.name = name; // name of a student object definition refers to a variable. The second parameter refers to the name createStudent function. The two are not the same
        }

It can be improved as follows:

        // Create a function
        function Student(name) {
            this.name = name; // this instance refers to the object constructor
        }

Note that comments in the code above.

Classes, instances

Use objects created with a constructor, we called a class of objects, also known as a constructor of a class.

By a constructor to create the object, called instances of the class.

instanceof

Use instanceof can check whether an object instance of a class.

The syntax is as follows:

Instanceof Object constructor

If so, it returns true; otherwise false.

Code Example:

      function Person() {}

      function Dog() {}

      was PERSON1 = new Person ();

      var dog1 = new Dog();

      console.log (person1 instanceof Person); // print the results: true
      console.log (dog1 instanceof Person); // print the results: false

      console.log (dog1 instanceof Object); // all objects are Object offspring. Therefore, the print result is: true

According to the last line of code above, you need to add this: all objects are Object descendants, so  任何对象 instanceof Object the results are returned true.

others

json Introduction

JSON: JavaScript Object Notation (JavaScript object representation).

The difference between the object and JSON literal: JSON attributes must be enclosed in double quotes quotes, literal objects may be omitted.

json example:

      {
            "name" : "zs",
            "age" : 18,
            "sex" : true,
            "sayHi" : function() {
                console.log(this.name);
            }
        };

Note: json in general put constants, arrays, objects, etc., but rarely in function.

Further, the object and no length json, json.length print result is undefined . Ever since, naturally also can not be used for looping through (because when traversing need to get the length of the length). json and objects are not used for looping through. Actual are for ... in 

json traversal methods:

json using  for...in...traversed , and an array of different traversal. as follows:

<script>
    var myJson = {
        "name": "smyhvae",
        "aaa": 111,
        "bbb": 222
    };

    // Method json traversal: in ... for ... 
    for ( var Key in myJson) {
        the console.log (Key);    // Get bond 
        the console.log (myJson [Key]); // get the value (binding property and a second value acquisition method) 
        the console.log ( " ------ " );
    }
</script>

Print Results:

 

Guess you like

Origin www.cnblogs.com/Vincent-yuan/p/12423885.html