Home  >  Article  >  Web Front-end  >  Xiaoqiang’s HTML5 mobile development road (27) - JavaScript review 2

Xiaoqiang’s HTML5 mobile development road (27) - JavaScript review 2

黄舟
黄舟Original
2017-02-04 14:16:141284browse

JavaScript object-oriented basic knowledge

1. How to define a class and use the following syntax to create a class

 function Person(name, age){ //习惯上第一个字母大写  
    //this修饰的变量称为属性  
    this.name = name;  
    this.age = age;  
    //如果属性值是一个函数,则这个属性就是一个方法  
    this.play = function(){  
        alert('play football...');  
    };  
}

2. How to create an instance of the class

var p = new Person('zs', 22);  
p.play();  
p.name;

3. Two other ways to create javascript objects

(1) First create an instance of the Object type, and then add new properties and methods

javascript is a Dynamic language, you can add new properties and methods to objects at runtime

var obj = new Object();  
obj.name = 'zs';  
obj.age = 22;  
obj.play = function(){  
    alert('play...');  
};

(2) Use "json" syntax

  var p = {'name':'zs','age':22};  
ar p = {'name':'zs','play':function(){  
alert('hello');  
};

or

var p = {name:'zs',age:22,marrid:false};  
var p = {name:'zs',play:function(){  
    alert('hello');  
}};

attribute value If it is a string, it must be enclosed in quotation marks (single and double)

The attribute value allows number, string, boolean, null, Object

var p = {name:'zs',  
    address:{  
        city:'beijing',  
        street:'ca'  
    }  
};

A complete example

<html>  
    <head>  
        <script>  
            function f1(){  
                //var p = {&#39;name&#39;:&#39;zs&#39;,&#39;age&#39;:22};  
                //var p = {name:&#39;zs&#39;,age:22,marrid:false};  
                var p = {name:&#39;zs&#39;,  
                    address:{  
                        city:&#39;beijing&#39;,  
                        street:&#39;ca&#39;  
                    }  
                };  
                //alert(p.name);  
                alert(p.address.city);  
            }  
            function f2(){  
                var arr = [  
                    {&#39;name&#39;:&#39;zs&#39;,&#39;age&#39;:22},  
                    {&#39;name&#39;:&#39;ls&#39;,&#39;age&#39;:32}  
                ];  
                alert(arr[1].name);  
            }  
        </script>  
    </head>  
    <body>  
        <input type="button" value="click me" onclick="f2();"/>  
    </body>  
</html>


The above is the content of Xiaoqiang’s HTML5 mobile development road (27) - JavaScript review 2. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn