Home >Web Front-end >JS Tutorial >JavaScript object-oriented - creation of simple objects and JSON objects
JavaScript is an object-based programming language, and its essence is actually object-oriented. The characteristic of object-oriented languages is that they all have the concept of classes, through which any number of objects with the same properties and methods can be created. But there is no concept of class in JavaScript. Objects in JavaScript are usually called prototype objects. We can create objects directly through Object. For example, the following code:
var person = new Object(); person.name = "张三"; person.age = 20; person.say = function(){ alert(this.name+","+this.age); }
In the above code, a person object is simply created through Object, and then 2 properties and 1 method are set for the person object.
The biggest problem caused by the objects created in the above way is that there is no class constraint, so the object cannot be reused, and there is no agreement, which will cause problems in operation.
Json object
We cannot transmit a JavaScript object over the network, only strings can be transmitted over the network. A feasible method of transmitting objects is to write the objects in XML format for transmission, for example:
<?xml version="1.0" encoding="utf-8"?> <preson> <id>1</id> <name>张三</name> <age>20</age> </person>
However, when using XML format for data transmission, a large number of additional tag strings will be generated during the transmission process, so The transmission efficiency is obviously not high. In order to solve these problems, people have developed another string object format: Json object format.
The full name of Json is javascript simple object notation, which is a simple data exchange format. The Json object is a JavaScript object, but it omits the tags in xml and uses {} to complete the description of the object.
The Json format defines attributes through attribute name: attribute value. Different attributes are separated by commas (,). The last attribute does not need to add a comma. For example, the following code defines a person object in Json format.
var person = { name : "张三", age:23, say:fuction(){ alert(this.name+","+this.age); } }
The properties and methods to call the person object are the same as those used by ordinary JavaScript objects, for example:
// 调用person的say方法 person.say();
We can also create object arrays through Json, and the creation method is the same as JavaScript arrays. Same.
var ps = [ {name:"Leon",age:22}, {name:"Ada",25} ];
After completing the creation of the array, we can also traverse the Json objects in the array.
for(var i = 0; i < ps.length; i++){ alert(ps[i].name); }
The above is JavaScript object-oriented - the creation of simple objects and the content of JSON objects. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!