Quick understanding of JavaScript syntax

Housewives: There are basic java and c, the need to quickly understand the syntax of JavaScript.

introduction

JavaScript is a lightweight scripting language. The so-called "scripting language" (script language), refers to the ability it does not have the development of the operating system, but is only used to control the writing of other large applications (such as browsers) "script."
JavaScript is also an embedded (embedded) language. It provides the core syntax itself is not a lot, can only be used to do some math and logic operations. JavaScript itself does not provide any relevant I / O (input / output) of the API, have to rely on the host environment (Host) provided, so that only the appropriate JavaScript embedded in a larger application environment, to call the low-level API provided by the host environment.

What can skip learning JavaScript

  1. The basic syntax
  2. Numerical
  3. String
  4. Objects
  5. function
  6. Array
  7. Arithmetic operators, comparison operators, etc.
  8. Regular Expression "slightly different, basically the same."

These and java c basically the same, it is recommended to skip, return encounter did not understand the point of view.

Here are some of the contents to learn:

  1. console objects with the console
  2. Standard Library
  3. Asynchronous operation
  4. JUDGMENT

console objects with the console

console objects

consoleObjects are JavaScriptnative objects, it's a bit like a Unixstandard system output stdoutand standard error stderr, can output the information to the console, and also provides a number of useful adjunct.

consoleThere are two common purposes:

  1. The debugger displays an error message page code at runtime.
  2. It provides a command line interface to interact with the web page code.

consoleObject browser implementations, included in the browser that comes with development tools. Chrome browser with "Developer Tools" (Developer Tools) as an example:

  • Elements: viewing the HTML source code and CSS code.
  • Resources: View various resource files (such as code files, font files CSS files, etc.) page load, and a variety of content (such as a local cache, Cookie, Local Storage, etc.) created on the hard disk.
  • Network: see page HTTP traffic situation.
  • Sources: view the script source code page loaded.
  • Timeline: View case various web behavior over time.
  • Performance: Performance View page of circumstances, such as CPU and memory consumption.
  • Console: used to run JavaScript commands.

console objects and methods

Object provides a variety of static methods console, used to interact with the console window.

console.log()

console.log method for console output information. It can accept one or more parameters, output to connect them.
console.log method automatically at the end of each output line breaks added.

console.table ()

For certain complex types of data, console.table method may be converted to tabular display.

var languages = [
  { name: "JavaScript", fileExtension: ".js" },
  { name: "TypeScript", fileExtension: ".ts" },
  { name: "CoffeeScript", fileExtension: ".coffee" }
];

console.table(languages);

console.count()

count method for counting, output how many times it is called.

function greet(user) {
  console.count();
  return 'hi ' + user;
}

greet('bob')
//  : 1
// "hi bob"

greet('alice')
//  : 2
// "hi alice"

greet('bob')
//  : 3
// "hi bob"

Greet function code above each call, console.count inside outputs method execution times.

This method may accepts a character string as a parameter, as a tag, to categorize the execution count.

console.assert()

console.assert method is mainly used in the program is running, will be evaluated, if the condition is not satisfied, it displays an error, but will not interrupt the program execution. This is equivalent to prompt the user, the internal state is incorrect.

It accepts two parameters, the first parameter is expression and the second argument is a string. Only if the first argument is false, will prompt an error, the output of the second parameter in the console, you will not have any results.

console.assert(false, '判断条件不成立')
// Assertion failed: 判断条件不成立

// 相当于
try {
  if (!false) {
    throw new Error('判断条件不成立');
  }
} catch(e) {
  console.error(e);
}

JSON object

Compared XML format, JSON format has two significant advantages: write simple, clear; in line with native JavaScript syntax, the engine can be directly processed by an interpreter, without additional add parsing code. So, JSON quickly accepted, the major sites have become the standard format for exchanging data, and written standards.

Each value is a JSON object, or the object may be an array, it may be a value of the original type. In short, only a value, can not be two or more values.

JSON has strict rules on the type and format of the value.

  1. Value only composite type or an array of objects, a function is not, regular expression object, the object date.

  2. Only four values ​​of the original type: String, value (to be represented in decimal), Boolean, and null (not used NaN, Infinity, -Infinity and undefined).

  3. The string must be double quotation marks, you can not use single quotes.

  4. Object key name must be in double quotes.

  5. After the last member of an array or object, not a comma.

JSON method

JSONThe object is a JavaScriptnative objects for processing JSONdata format. It has two static methods: JSON.stringify()和JSON.parse().

JSON.stringify()

A method for JSON.stringify JSON string into a value. The string line with JSON format, and may be reduced JSON.parse method.

JSON.stringify('abc') // ""abc""
JSON.stringify(1) // "1"
JSON.stringify(false) // "false"
JSON.stringify([]) // "[]"
JSON.stringify({}) // "{}"

JSON.stringify([1, "false", false])
// '[1,"false",false]'

JSON.stringify({ name: "张三" })
// '{"name":"张三"}'

The above types of code values, conversion to JSON string.

Note that for the original string type, the conversion results quotation marks.

JSON.stringify(false) // "false"
JSON.stringify('false') // "\"false\""

The above code, if not the inner double quotation marks, the future reduction of the time, the engine can not know the original value is a Boolean value, or string.

The second parameter

JSON.stringify method may also accept an array, as the second parameter specifies the need to turn into a string attribute.

var obj = {
  'prop1': 'value1',
  'prop2': 'value2',
  'prop3': 'value3'
};

var selectedProperties = ['prop1', 'prop2'];

JSON.stringify(obj, selectedProperties)
// "{"prop1":"value1","prop2":"value2"}"

In the above code, JSON.stringifythe second argument specifies the method, only turn prop1and prop2two properties.
Output: {"prop1":"value1","prop2":"value2"}
array similar to the white list, only the properties of objects valid, invalid array.

JSON.stringify(['a', 'b'], ['0'])
// "["a","b"]"

JSON.stringify({0: 'a', 1: 'b'}, ['0'])
// "{"0":"a"}"

In the above code, the second argument specifies only turn JSON format attribute 0, it is actually the array is invalid, valid only for the object.

JSON.parse()

JSON.parse method for converting a string to a value corresponding to JSON.

JSON.parse('{}') // {}
JSON.parse('true') // true
JSON.parse('"foo"') // "foo"
JSON.parse('[1, 5, "false"]') // [1, 5, "false"]
JSON.parse('null') // null

var o = JSON.parse('{"name": "张三"}');
o.name // 张三

Asynchronous and promise

Callback

Asynchronous operation callback function is the most basic method.

Here are two functions f1and f2programming intentions are f1 f2 must wait until the execution is complete before execution.

function f1() {
  // ...
}

function f2() {
  // ...
}

f1();
f2();

The problem is that the above code, if f1 is asynchronous operation, f2 will be executed immediately, not wait until the end of f1 and then executed.

In this case, consider rewriting f1, f1 to f2 written callback function.

function f1(callback) {
  // ...
  callback();
}

function f2() {
  // ...
}

f1(f2);

Advantage of the callback function is a simple, easy to understand and implement, the disadvantage is not conducive to reading the code and maintenance, high coupling between the various parts (Coupling), so that the program structure confusing, difficult to track the process (in particular a plurality of nested callback case), and each task can only specify a callback function.

Event Listeners

Another idea is to use the event-driven model. Perform asynchronous tasks does not depend on the order code, but on whether an event occurred.
Or in f1and f2example. First, to f1bind an event (jQuery wording used here).
f1.on('done', f2);
Above this line of code means that, when f1the occurrence of donean event, is executed f2. Then, f1rewrite:

function f1() {
  setTimeout(function () {
    // ...
    f1.trigger('done');
  }, 1000);
}

The above code, f1.trigger('done')said after the execution is complete, immediately triggering doneevent, which started f2.

The advantage of this method is relatively easy to understand, you can bind multiple events, each event can specify multiple callback functions, and can be "decoupling" (decoupling), in favor of modular. The disadvantage is that the entire program should be turned into an event-driven, run the process will become very clear. Read the code, it is hard to see the main flow.

Promise objects

Promise JavaScript objects are asynchronous operations solution that provides a unified interface for asynchronous operation. It plays the role of a proxy (Proxy), acts as an intermediary between the asynchronous operation of the callback function, includes an interface that asynchronous operation synchronous operation. Promise allows asynchronous operation to write, just write in the synchronous operation of the process, rather than layers of nested callback function.
First, Promise is an object, but also a constructor.

function f1(resolve, reject) {
  // 异步代码...
}

var p1 = new Promise(f1);

The above code, the Promiseconstructor takes a callback function f1as a parameter, f1which is the code for asynchronous operation. Then, the return p1is a Promiseexample.

PromiseThe idea is that all asynchronous tasks return a Promiseinstance. PromiseExamples of a thenmethod to specify the next callback.

var p1 = new Promise(f1);
p1.then(f2);

The above code, f1the completion of the asynchronous operation execution, executesf2

The traditional wording may need to be f2as a callback function passed f1, such as written f1(f2), after the asynchronous operation is complete, the f1internal call f2. PromiseMaking f1and f2became a chain wording. Not only to improve readability, and is particularly convenient for nested callback function.

// 传统写法
step1(function (value1) {
  step2(value1, function(value2) {
    step3(value2, function(value3) {
      step4(value3, function(value4) {
        // ...
      });
    });
  });
});

// Promise 的写法
(new Promise(step1))
  .then(step2)
  .then(step3)
  .then(step4);

We can see from the above code, after the use of Promises, the program flow becomes very clear, very readable. Note that, for ease of understanding, an example of generating the above format Promise code made simplified, real hereinafter refer to the syntax.
In general, conventional callback function makes code writing jumbled, becomes horizontal development rather than down the development. Promise is to solve this problem so that the process can be written as asynchronous synchronization process.

Promise originally just an idea raised by the community, some of the library the first to achieve this functionality. ECMAScript 6 writes language standards, the current native support JavaScript Promise objects.

Promise state object

Promise objects through own state, to control the asynchronous operation. Promise instance has three states.

  • Asynchronous operation is not completed (Pending)
  • Asynchronous operation was successful (fulfilled)
  • Asynchronous operation failed (Rejected)

Inside the above three states, fulfilledand rejectedtogether referred to as resolved(finalized).

The three ways to change the status of only two.

  • From the "unfinished" to "success"
  • From the "unfinished" to "failure"

Once the status changes on the solidification, there will be no change in the new state. Promise This is the origin of the name, which in English means "promise" that once promised results, it may not be changed again. This also means that the state change Promise instances may occur only once.

Therefore, the final result Promise of only two.

  • Asynchronous operation is successful, Promise example returns a value (value), the state becomes fulfilled.
  • Asynchronous operation failed, Promise instance throws an error (error), the state changes to rejected

Promise Constructor

JavaScriptProviding native Promiseconstructor to generate Promiseexamples:

var promise = new Promise(function (resolve, reject) {
  // ...

  if (/* 异步操作成功 */){
    resolve(value);
  } else { /* 异步操作失败 */
    reject(new Error());
  }
});

In the above code, Promisethe constructor function accepts as a parameter, two parameters of the function are respectively resolveand reject. They are two functions by JavaScriptproviding engines do not have to achieve.

resolveFunction returns the Promisestatus of the instance from "unfinished" to "success" (i.e., the pendingchanges fulfilled), upon successful call asynchronous operation, and the result of the asynchronous operation, to pass out as a parameter. rejectFunction returns the Promisestatus of the instance from "unfinished" to "failed" (i.e., the pendingchanges rejected), when an asynchronous operation call fails, and the asynchronous operation errors may be, as a parameter to pass out.

Promise.prototype.then()

PromiseExamples of the thenmethod for adding the callback function.

thenThe method can accept two callback functions, a first asynchronous operation is successful (changed fulfilledstate) is the callback function, the second is an asynchronous operation fails (becomes a rejectedcallback function (the parameter may be omitted) when). Once the status changed, call the appropriate callback function.

var p1 = new Promise(function (resolve, reject) {
  resolve('成功');
});
p1.then(console.log, console.error);
// "成功"

var p2 = new Promise(function (resolve, reject) {
  reject(new Error('失败'));
});
p2.then(console.log, console.error);
// Error: 失败

The above code, p1and p2both Promiseinstances, their thenmethod of binding two callback functions: successful callback function console.logwhen the callback fails console.error(can be omitted). p1The state becomes successful, p2the state becomes a failure, the corresponding callback function will receive an asynchronous operation return value, then the output in the console.

thenChain method can be used.

p1
  .then(step1)
  .then(step2)
  .then(step3)
  .then(
    console.log,
    console.error
  );

The above code, p1followed by four then, which means there are four sequentially callback function. As long as the state to step in front fulfilled, it will be followed by the implementation immediately after the callback function.

The last thenmethod, the callback function is console.logand console.error, a little important differences in usage. console.logShow only step3return value, and console.errorcan be displayed p1, step1, step2, step3in any of the errors. For example, if step1the state becomes rejected, then step2, and step3it will not be implemented (because they are resolvedcallbacks). PromiseStart looking for the next first rejectedcallback function, in the above code console.error. That is, Promisegiven an object transitive.

Example: images load

Here is the picture of Promise finished loading.

var preloadImage = function (path) {
  return new Promise(function (resolve, reject) {
    var image = new Image();
    image.onload  = resolve;
    image.onerror = reject;
    image.src = path;
  });
};

The above code, imageis an example of a picture object. It has two event listeners attribute, onloadattribute called after the picture is loaded, onerrorproperty call fails to load.

The above preloadImage()function is used as follows.

preloadImage('https://example.com/my.jpg')
  .then(function (e) { document.body.append(e.target) })
  .then(function () { console.log('加载成功') })

The above code, after the picture is loaded, onloadproperty returns an event object, so the first then()method of the callback function, will receive the event object. The object targetattribute is generated after the image is loaded DOMnodes.

JUDGMENT

JavaScript DOM is operating web interface, called the "Document Object Model" (Document Object Model). It is the role of the web page into a JavaScript object, which can perform various operations (such as add or delete content) script.

According browser DOM model, structured documents (such as HTML and XML) parsing into a series of nodes, and then a tree structure (DOM Tree) from these nodes. All the nodes and the final tree, has standardized external interfaces.

DOM is just an interface specification, you can use a variety of language. Strictly speaking, DOM is not part of the syntax of JavaScript, but JavaScript DOM manipulation is the most common tasks, left the DOM, JavaScript can not control page. On the other hand, JavaScript is the language most commonly used DOM operations. JavaScript is described later in this implementation and usage of the DOM standard.

node

DOM minimum constituent units, called nodes (node). Tree structure (DOM tree) of the document, that is the various types of nodes. Each node can be seen as a leaf document tree.

There are seven types of nodes.

Browser provides a native node object Node, above the seven nodes are inherited Node, so it has some common properties and methods.

Guess you like

Origin www.cnblogs.com/samanian/p/12232105.html