JavaScript III (Object Thinking)

JavaScript is not an object-oriented programming language, but it is object-based. Every function in JavaScript can be used to create an object, and the returned object is both an instance of that object and an instance of object. 

1. Objects and associative arrays

An object in JavaScript is essentially an associative array, just like the Map data structure in Java, which consists of a set of key-value pairs. The difference is that the value of a JavaScript object can be not only a value, but also a function, and the function is the object Methods.

When the value is the value of the basic type or the value of the composite type, then the value is the attribute value of the object.

                                                                                                                                                                                                                                                      

Therefore, when accessing a JavaScript object, not only the form of obj.propName can be used, but also the form of obj[propName] can be used. Sometimes this form must be used.

 

<script type="text/javascript">
    function Person(name,age)
    {
      this.name = name;
      this.age = age;
      this.info = function(){
        alert( "info method" );
      }
    }

    var p = new Person('Sherman',30);
    for(propName in p)
    {
      document.writeln( "The property value of the "+propName+" property of the p object is "+p[propName]+'<br/>' )
    }
  </script>

 

 

2. Inheritance and prototype

JavaScript does not provide explicit inheritance syntax. Each object is a subclass of object, so all objects are equal, and there is no direct parent-child relationship between objects.

JavaScript provides some built-in classes, through which you can easily create your own objects.

JavaScript is a dynamic language that allows to freely add properties and methods to objects. When a program assigns a value to a property that does not exist in an object, it can be considered to add properties to the object, for example

var p = {}
p.age=30;
p.info = function(){
alert( 'info method' );
}

 All JavaScript classes have a protoType property. If you add properties and methods to the protoType properties of a JavaScript class, it can be regarded as an extension of the original class. We can understand it as: the class with the added protoType attribute inherits the original class,

This is JavaScript's pseudo-inheritance mechanism. See the code below:

<script type="text/javascript">
    function Person(name,age)
    {
      this.name = name;
      this.age = age;
      this.info = function(){
        document.writeln('姓名:'+this.name+'<br/>');
        document.writeln('年龄:'+this.age+'<br/>');
      }
    }
    var p1 = new Person('Sherman',23);
    p1.info();

    Person.prototype.walk = function()
    {
     document.writeln( this .name+'Walk slowly...<br/>' )
    }
    document.writeln('<hr/>');
    var p2 = new Person('Leegang',30);
    p2.walk();
    p1.walk();
  </script>

 

Note that the essence of pseudo-inheritance is to modify the original class, not to generate a new subclass

JavaScript built-in classes can be extended by using the protoType property

<script type="text/javascript">
    Array.prototype.indexof = function(obj)
    {
      var result = -1;
      for(var i = 1;i < this.length;i++)
      {
        if(this[i] == obj){
          result = 1;
          break;
        }
      }
      return result;
    }

    var arr = [4,5,7, -2 ];
    alert(arr.indexof(-2));
  </script>

 In addition, protoType represents the prototype object of the class. By default, the protoType property value of a JavaScript class is an object. Setting the protoType of a JavaScript class as an instance of the parent class can implement JavaScript inheritance, for example:

<script type="text/javascript">
    function Person(name,age)
    {
      this.name = name;
      this.age = age;
    }
    Person.prototype.sayHello = function()
    {
      console.log( this .name+'hello you' );
    }

    var per = new Person('Bull Demon King',30000 );
    per.sayHello();

    function Student(grade)
    {
      this.grade = grade;
    }

    Student.prototype = new Person('Unnamed', 0 );
    Student.prototype.intro = function()
    {
      console.log( "%s is a student, in grade %d", this .name, this .grade);

    }

    var stu = new Student (5 );
    stu.name = 'Sun Wukong' ;

    console.log(stu instanceof Student);//输出true
    console.log(stu instanceof Person);//输出true
    stu.sayHello();
    stu.intro();
  </script>

3. The constructor implements pseudo-inheritance

The implementation code is as follows:

<script type="text/javascript">
  function Person(name,age)
  {
    this.name = name;
    this.age = age;
    this.sayHello = function()
    {
      console.log( this .name+'Hello!' );
    }
  }

  var per = new Person('Bull Demon King',30000 );
  per.sayHello();

  function Student(name,age,grade)
  {
    this.a = Person;
    this.a(name,age);
    this.grade = grade;
  }

  Student.prototype.intro = function()
  {
    console.log( "%s is a student, in grade %d", this .name, this .grade);
  }

  var stu = new Student('Monkey King',34,5 );
  console.log(stu instanceof Student);//输出true
  console.log(stu instanceof Person);//输出true
  stu.sayHello();
  stu.intro();
</script>

 4. Use apply or call to implement pseudo-inheritance

The implementation code is as follows:

<script type="text/javascript">
    function Person(name,age)
    {
      this.name = name;
      this.age = age;
      this.sayHello = function()
      {
        console.log( this .name+'Hello!' );
      }
    }

    var per = new Person('Bull Demon King',30000 );
    per.sayHello();

    function Student(name,age,grade)
    {
      //this.a = Person;
     // this.a(name,age);
      Person.call(this,name,age);
      Person.apply(this,[name,age]);
      this.grade = grade;
    }

    Student.prototype.intro = function()
    {
      console.log( "%s is a student, in grade %d", this .name, this .grade);
    }

    var stu = new Student('Monkey King',34,5 );
    console.log(stu instanceof Student);//输出true
    console.log(stu instanceof Person);//输出true
    stu.sayHello();
    stu.intro();
  </script>

The output is the same as above

5. Create objects

There are roughly three ways to create objects in JavaScript:

1. Use the new keyword to call the constructor to create an object

2. Use the object class to create objects

// Create a default object 
var obj = new Object();

This is an empty object without any properties and methods, but JavaScript is a dynamic language that can dynamically add properties and methods to objects

The following code:

<script type="text/javascript">
    var myobj = new Object();
    myobj.name = 'Sherman';
    myobj.age = 34;
    document.writeln(myobj.name+myobj.age);//输出Sherman34
  </script>

 

3. Create objects using Json syntax

 When using Json syntax to create JavaScript objects, property values ​​can be not only ordinary strings, but also any basic data type, arrays, functions, or even objects created by another JSON syntax.

Person = 
      {
        name:'Sherman',
        gender:'male',
        son:{
          name: 'guoguo' ,
          grade:1
        },
        info:function()
        {
          document.writeln( 'Name:'+ this.name +'gender:'+ this.gender );
        }
      }
  </script>

Arrays can also be created using JSON syntax

arr = [vlue1,value2,value3,...]

The following code creates a complex JSON object

Person =
      {
        name:'Sherman',
        age:29,
        schools:[ 'Primary', 'Secondary', 'University' ],
        parents:[{
          name:'father',
          age:49,
          address: 'Guangzhou'
        },{
          name:'mother',
          age:51,
          address: 'Shenzhen'
        }]
      }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325510101&siteId=291194637