Home  >  Article  >  Web Front-end  >  Detailed explanation of objects and JSON for getting started with JavaScript_Basic knowledge

Detailed explanation of objects and JSON for getting started with JavaScript_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 18:00:49833browse

JavaScript objects have little similarity with objects in traditional object-oriented languages. In traditional object-oriented languages, to create an object, you must first have a template for the object: a class, which defines the properties of the object and the methods for operating these properties. Construct an object through instantiation, then use collaboration between objects to complete a function, and complete the entire project through a collection of functions. There is no concept of class in JavaScript. With the dynamic nature of JavaScript, we can create an empty object (instead of a class) and improve the function of the object by dynamically adding attributes to the object.

JSON is the literal value of an object in JavaScript and a representation method of an object. By using JSON, you can reduce intermediate variables and make the structure of the code clearer and more intuitive. Using JSON, objects can be constructed dynamically without having to instantiate them through classes, which greatly improves the efficiency of coding.

Javascript object

JavaScript object is actually a collection of attributes. The collection here is equivalent to the mathematical collection, that is, it has determinism, disorder and Mutuality, that is to say, given a JavaScript object, we can clearly know whether an attribute is an attribute of the object. The attributes in the object are unordered and different (if there is one with the same name, then the following The declared overrides the first declared).

Generally speaking, when we declare an object, the object is often just an empty collection and does not contain any attributes. By continuously adding attributes, the object becomes a fully functional object without having to create A class, and then instantiate the class this mode, so that our code has higher flexibility, we can add or delete the properties of the object arbitrarily.

If readers have experience with python or other similar dynamic languages, they can better understand JavaScript objects. The JavaScript object itself is a dictionary, or a Map in the Java language, or as An associative array associates an object through a key, and the object itself can be an object. According to this definition, we can know that JavaScript objects can represent any complex data structure.

Object attributes

Attributes are composed of key-value pairs, that is, the name of the attribute and the value of the attribute. The name of the property is a string, and the value can be any JavaScript object (everything in JavaScript is an object, including functions). For example, declare an object:

Copy code The code is as follows:

//Declare an object
var jack = new Object();
jack.name = "jack";
jack.age = 26;
jack.birthday = new Date(1984, 4, 5);

//Declare another object
var address = new Object();
address.street = "Huang Quan Road";
address.xno = "135";

//Assign the addr attribute to the object address
jack.addr = address;

This way of declaring objects is completely different from the traditional OO language. It gives us great advantages Flexibility to customize the behavior of an object.

The object attributes are read through the dot operator (.). For example, the addr attribute of the jack object in the above example can be obtained in the following ways:
Copy code The code is as follows:
var ja = jack.addr;
ja = jack[addr];

Later In order to avoid this situation, imagine that the object has a property that itself contains a dot (.), which is legal in JavaScript. For example, the name is foo.bar. When using jack.foo.bar, the interpreter will mistakenly It is thought that there is a bar field under the foo attribute, so it can be accessed using jack[foo.bar]. Generally speaking, when we develop a general toolkit, we should not make any assumptions about possible user input. Correctness can always be guaranteed through the form of [attribute name].

Attributes and Variables

In Chapter 2, we explained the concept of variables. In this chapter, readers may have noticed that the behavior of the two is very similar. , in fact, the properties of the object and the variables we mentioned before are actually the same thing.

When the JavaScript engine is initialized, it will build a global object. In the client environment, this global object is window. If you need to reference this global object in other JavaScript environments, you only need to declare it in the top-level scope (that is, the scope outside all function declarations):

Copy code The code is as follows:
var global = this;

The variables we declare in the top-level scope will be saved as properties of the global object. From this point of view, variables are actually properties. For example, on the client side, code like this often appears:

Copy code The code is as follows:
var v = "global";
var array = ["hello", "world"];
function func(id){
var element = document.getElementById(id);
/ /Do some operations on element
}

is actually equivalent to:
Copy the code The code is as follows:

window.v = "global";
window.array = ["hello", "world"];
window.func = function(id){
var element = document.getElementById(id);
//Do some operations on element
}

Prototype object
Prototype (prototype), which is JavaScript A unique concept, through the use of prototypes, JavaScript can establish inheritance in its traditional OO language, thereby reflecting the hierarchical relationship of objects. JavaScript itself is based on prototypes. Each object has a prototype attribute. The prototype itself is also an object, so it can also have its own prototype, thus forming a chain structure.
When accessing an attribute, the parser needs to traverse the chain structure from bottom to top until it encounters the attribute, then returns the value corresponding to the attribute, or encounters an object with a null prototype (the prototype of JavaScript's base object Object attribute is null), if this object still does not have this attribute, undefined is returned.
Let’s look at a specific example below:
Copy code The code is as follows:

//Declare an object base
function Base(name){
this.name = name;
this.getName = function( ){
return this.name;
}
}
//Declare an object child
function Child(id){
this.id = id;
this. getId = function(){
return this.id;
}
}
//Point the child’s prototype to a new base object
Child.prototype = new Base("base" );
//Instantiate a child object
var c1 = new Child("child");
//c1 itself has the getId method
print(c1.getId());
//Since c1 "inherited" the getName method from the prototype chain, you can access
print(c1.getName());

to get the result:
child
base
Since the prototype chain is traversed from bottom to top, the attribute value encountered first is returned first. Through this mechanism, the overloading mechanism can be completed.
this pointer
The most confusing thing in JavaScript is probably the this pointer. In traditional OO languages, this pointer is declared in the class and represents the object itself. In JavaScript, this represents the current Context, a reference to the caller. Here we can look at a common example:
Copy code The code is as follows:

// Define a person with the name jack
var jack = {
name : "jack",
age : 26
}
//Define another person with the name abruzzi
var abruzzi = {
name : "abruzzi",
age : 26
}
//Define a global function object
function printName(){
return this.name;
}
//Set the context of printName to jack, and this at this time is jack
print(printName.call(jack));
//Set the context of printName to abruzzi, at this time this For abruzzi
print(printName.call(abruzzi));

Running result:
jack
Abruzzi
It should be noted that the value of this is not how the function is called It is determined by declaration, but is determined by how the function is called. This is completely different from traditional object-oriented languages. Call is a function on Function, which is described in detail in Chapter 4.
Using objects
Objects are the basis of JavaScript. We use JavaScript to complete programming work by using objects. This section uses some examples to learn how to use JavaScript objects:
There are three types of object declarations Method:
◆ Construct a new object through the new operator scope Object object, and then dynamically add attributes to build an object from scratch.
◆ Define the "class" of the object: prototype, and then use the new operator to build new objects in batches.
◆ Use JSON, which will be explained in detail in the next section
In this section we will explain the second method in detail, such as:
Copy code The code is as follows:

//Define a "class", Address
function Address(street, xno){
this.street = street || 'Huang Quan Road';
this.xno = xno || 135;
this.toString = function(){
return "street : " this.street ", No : " this.xno;
}
}
//Define another A "class", Person
function Person (name, age, addr) {
this.name = name || 'unknown';
this.age = age;
this.addr = addr || new Address(null, null);
this.getName = function () {return this.name;}
this.getAge = function(){return this.age;}
this.getAddr = function(){return this.addr.toString();}
}
//Create two objects through the new operator. Note that these two objects are independent entities
var jack = new Person('jack', 26, new Address('Qing Hai Road', 123));
var abruzzi = new Person('abruzzi', 26);
//View results
print (jack.getName());
print(jack.getAge());
print(jack.getAddr());
print(abruzzi.getName());
print(abruzzi .getAge());
print(abruzzi.getAddr());

The running results are as follows:
jack
26
street : Qing Hai Road, No : 123
abruzzi
26
street : Huang Quan Road, No : 135

JSON and its use

JSON stands for JavaScript Object Notation (JavaScript Object Notation), which represents an object through literals. This method can be used from simple to complex. For example:
Copy code The code is as follows:

var obj = {
name : " abruzzi",
age : 26,
birthday : new Date(1984, 4, 5),
addr : {
street : "Huang Quan Road",
xno : "135"
}
}

This method is obviously much simpler than the above example. There are no redundant intermediate variables and it clearly expresses the structure of an object like obj. In fact, most experienced JavaScript programmers prefer to use this representation, including many JavaScript toolkits such as jQuery, ExtJS, etc., which use JSON extensively. JSON has actually been used as a data exchange format between the front-end and the server-side. The front-end program sends JSON objects to the back-end through Ajax. The server-side script parses the JSON, restores it to a server-side object, and then does some processing and feeds it back to the front-end. It is a JSON object, using the same data format, which can reduce the probability of errors.

Moreover, the data in JSON format itself is recursive, that is, it can express any complex data form. The writing method of JSON is very simple, that is, key-value pairs enclosed in curly braces. The key-value pairs are separated by colons, and the value can be any JavaScript object, such as simple objects String, Boolean, Number, Null, or complex objects such as Date. , Object, other customized objects, etc.

Another application scenario of JSON is: when a function has multiple return values, in traditional object-oriented languages, we need to organize an object and then return it, but JavaScript does not need to be so troublesome at all. For example:

Copy code The code is as follows:
function point(left, top){
this.left = left;
this.top = top;
//handle the left and top
return {x: this.left, y:this.top};
}

Just dynamically construct a new anonymous object and return it:

Copy the code The code is as follows:
var pos = point(3, 4);
//pos.x = 3;
//pos.y = 4;

Use JSON to return the object, this object There can be arbitrarily complex structures, even including function objects.

In actual programming, we usually need to traverse a JavaScript object, and we know nothing about the contents of the object in advance. How to do it? JavaScript provides syntactic sugar in the form of for..in:

Copy code The code is as follows:
for(var item in json){
//item is the key
//json[item] is the value
}

This mode is very useful, for example, in In actual WEB applications, some attributes need to be set for a page element. These attributes are not known in advance, such as:

Copy codeThe code is as follows:
var style = {
border:"1px solid #ccc",
color:"blue"
};

그런 다음 DOM 요소에 이러한 속성을 동적으로 추가합니다.

코드 복사 코드는 다음과 같습니다.
for(var item in style){
//jQuery 선택기 사용
$("div#element").css(item, style[item])
}

물론 jQuery에는 이러한 작업을 수행하는 더 좋은 방법이 있습니다. 다음은 단지 예일 뿐입니다. $("div#element")에 속성을 추가하면 스타일 구조가 변경되지 않습니다. 분명한.

또한 예를 들어 일부 사용자 정의 설정을 수집해야 하는 경우 JSON 개체를 노출할 수도 있으며, 사용자는 설정해야 하는 콘텐츠로 JSON을 채운 다음 우리 프로그램이 그것을 처리할 것입니다.

코드 복사 코드는 다음과 같습니다.
기능 사용자 정의(옵션){
this.settings = $.extend(기본값, 옵션)
}
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