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
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 (m.sbmmt.com)!