Selected contents of JavaScript language essence


Recently reading《The essence of JavaScript language》This book is written byDouglas CrockfordDouglas CrockfordIt’s a guy fromYahoo!SeniorJavaScript architectTo create and maintainJSONJavaScript object notation)The format is well known. He will regularly publish relevant information in various meetingsAdvanced JavaScriptA keynote speech. He is also.ESMAscriptOne of the members of the Committee.
I wanted to write a post reading article, but think about it《The essence of JavaScript language》It’s the first book I read in JavaScript, which is to broaden my horizons, so I only have a summary of this book in my mind, not to mention a sense of it. And my purpose is to save time reading this book and help you understand the general content. I will try to convey the essence of this book to my friends who want to read it.
Note: this book is not for beginners, nor is it a stupid tutorial.


  1. There are two annotation forms of javascript: / * * / (block annotation) and / / (line annotation)

  2. The character pair of block comment may appear in the literal amount of regular expression, so block comment is relatively unsafe

    For example:
    var rm_a = /a*/.match(s);
  3. The author suggests avoiding the / * * / comment as much as possible and replacing it with / /.


  1. An identifier begins with a letter and can optionally be followed by one or more letters, numbers, or underscores.

  2. Identifiers cannot use these reserved words:

boolean    break    byte
case    catch    char    class    const    continue
debugger    default    delete    do    double
else    enum    export    extends
false    final    finally    float    for    function
if    implements    import    in    instanceof    int    interface
native    new    null
package    private    protected    public
short    static    super    switch    synchronized
this    throw    throws    transient    true    try    typeof
var    volatile    void
while    with


  1. JavaScript onlyOneNumber type. It is internally represented as a 64 bit floating-point number, just like Java’s double number type.

  2. If a number literal has an exponential part, the value of the literal is equal to the power of the number before e multiplied by the number after e of 10. So 100 and 1E2 are the same number.

  3. Digital ownershipMethod, JavaScript has an objectMath, which contains a set of methods for numbers.
    For example, you can useMath.floor(number)Method to convert a number to an integer.

Character string

  1. JavaScript has no character type. To represent a character, simply create a string that contains only one character.

  2. String has alengthAttribute. For example,“seven”.lengthIt’s 5.

  3. Strings also have some methods. For example,‘cat’.toUpperCase( ) === ‘CAT’


  1. When the VaR statement is used inside a function, it defines theprivate variable

  2. Statements are usually executed from top to bottom. JavaScript can use conditional statements(If and switch), loop statement(While, for, and do), force jump statement(Break, return and throw)And function calls to change the sequence of execution


1. [] () --- extract attribute and call function
 2. * /% --- multiplication, division and remainder
 3. Logic and
 4. Logical or
 5.? : ------ three yuan

Ternary operator? Followed by another expression, followed by:, followed by a third expression.
Ternary operator? There are three operands. If the value of the first operand is true, the value of the second operand is generated; if it is false, the value of the third operand is generated.


Objects in JavaScript are typeless(class-free), objects can contain other objects.
JavaScript contains the characteristics of a prototype chain that allows an object to inherit the properties of another object. Using it correctly can reduce the time and memory consumed in object initialization.
1. Object literals

  • It is illegal to include the connector ‘-‘ in the identifier of JavaScript, but the underscore ‘?’ is allowed,

  • So put it in quotation marks“first-name”Is required.

2. Retrieve

  • To retrieve the value contained in an object, you can enclose a string expression in the [] suffix.

  • If the string expression is a string literal, then the. Notation can also be used instead.

  • The. Notation is preferred because it is more compact and readable.

  • If you try to retrieve the value of a member property that does not exist, theundefined

  • Attempting to take a value from the undefined member property will result in a typeerror exception. In this case, you can use the & & operator to avoid errors.

3. Prototype

  • Each object is connected to a prototype object, and it can inherit properties from it. All objects created by object literals are connectedObject.prototype, which is the standard object in JavaScript.

  • When you create a new object, you can choose an object as its prototype. The implementation mechanism provided by JavaScript is messy and complex, but it can be obviously simplified. We will giveObjectAdd one morecreateMethod. This method creates a new object that uses the original object as its prototype.

if(typeof Object.beget !== 'function') {
    Object.create = function(o) {
        var F = function() {};
        F.prototype = o;
        return new F();
var another_stooge = Object.create(stooge);
  • Prototype connections do not work when updated. When we make changes to an object, the prototype of the object is not affected.

  • If we try to get a property value of an object, but the object does not have the property name, JavaScript will try to get the property value from the prototype object. If the prototype object does not change its properties, then look for it from its prototype, and so on, until it finally reaches the destinationObject.prototype

  • If the desired attribute does not exist in the prototype chain at all, the result isundefinedValue. This process is calledEntrust

  • Prototype relationship is a dynamic relationship. If we add a new attribute to the prototype, it will be immediately visible to all objects created based on the prototype.

4. Reflection

  • It’s easy to examine an object and determine what properties it has, as long as you try to retrieve the property and verify the value.TypeofOperators are useful for determining the type of property:

typeof flight.number            //'number'
typeof flight.status            //'string'
typeof flight.arrival           //'object'
typeof flight.manifest          //'undefined'
  • Note that any attribute in any prototype chain produces a value:

typeof flight.toString           //'function'
typeof flight.constructor        //'function'

There are two ways to deal with these unwanted properties. The first is to have your program check and discard properties with values as functions. The other is to usehasOwnPropertyMethod, if the object has unique properties, it will returntrue
hasOwnPropertyMethod does not check the prototype chain.

fligth.hasOwnProperty('number')         //true
flight.hasOwnProperty('constructor')    //false

5. Enumeration

  • for inStatement can be used to traverse all property names in an object. Changing the enumeration process will list all the properties – including those in functions and prototypes you may not care about – so there’s no need to filter out values you don’t want. The most commonly used filters arehasOwnPropertyMethod, and usetypeofTo exclude functions:

var name;
for(name in another_stooge) {
    if(typeof another_stooge[name] !== 'function') {
        document.writeln(name + ':' + another_stooge[name]);
  • The order in which property names appear is uncertain, so be prepared for any possible order. If you want to make sure that the attributes appear in a specific order, the last resort is to avoid using them at allfor inInstead, create an array that contains the property names in the correct order:

var i;
var propertier = {
for(i = 0; i< properties.length; i += 1) {
    document.writeln(properties[i] + ':' + another_stooge[properties[i]]);

adoptforInstead offor in, we can get the attributes we want without worrying about the possibility of discovering the attributes in the prototype chain, and we get their values in the right order.

6. Delete

  • The delete operator can be used to delete an object’s properties. If the object contains the property, the property is removed. It does not touch any objects in the prototype chain.

  • Deleting an object’s properties may expose properties from the prototype chain:

another_stooge.nickname            //'Moe'
delete another_stooge.nickname;
another_stooge.nickname            //'Curly'

7、 Global Abatement

  • Global variables weaken the flexibility of the program and should be avoided.

  • One way to minimize the use of global variables is to create a unique global variable for your application value:

var MYAPP = {};

This variable becomes the container of your application:

MYAPP.stooge = {
    "first-name": "joe",
    "last-name": "Howard"
MYAPP.flight = {
    airline: "Oceanic",
    departure: {
        IATA: "SYD",
        city: "Sydney"
  • As long as the global resources are included in a namespace, the possibility of conflicts between your program and other applications, components or class libraries will be significantly reduced. The program will also be easier to read, because it’s clear that,MYAPP.stoogeIt points to the top-level structure. There is also an effective way to reduce global pollution. The way to hide information is toclosure


1. Function literal

  • Function objects are created by function literals:

//Create a variable named add and assign it a function that adds two numbers
var add = function(a,b) {
    return a + b;

The function literal consists of four parts.

  • The first part is reserved wordsfunction

  • The second part is the function name, which can be omitted. Function can call itself recursively by its name. This name may also be used by debuggers and development tools to identify functions. If a function is not named, it is calledAnonymous function

  • The third part is a set of parameters enclosed in parentheses. Multiple parameters are separated by commas. The names of these parameters are defined as variables in the function. They are not initialized toundefinedIs initialized to the value of the actual supplied parameter when the function is called.

  • The fourth part is a set of statements enclosed in curly braces. These statements are the body of the function and they are executed when the function is called.

  • Function literals can appear wherever expressions are allowed. An internal function can not only access its own parameters and variables, but also freely access the parameters and variables of the parent function in which it is nested. Function objects created by function literals contain a connection to an external context. This is calledClosure。 It’s the source of JavaScript’s powerful expression!

2. Call invocation
Calling a function pauses the execution of the current function, passing control and parameters to the new function. In addition to the formal parameters defined at the time of declaration, each parameter takes over two additional parameters:thisandarguments。 parameterthisVery important in object-oriented programming, its value depends on the mode of invocation. There are four call modes in javascript:Method call mode, function call mode, constructor call mode and apply call mode。 These modes are used when initializing key parametersthisThere are differences on.
A call operator is a pair of parentheses following any expression that produces a function value. Parentheses can contain 0 or more expressions separated by commas. Each expression produces a parameter value. Each parameter value is given the formal parameter name defined when the function is declared. WhenActual parameters and formal parametersDoes not cause runtime errors when the number of does not match. If there are too many actual parameter values, the exceeded parameter values are ignored. If the actual parameter value is too small, the missing value is replaced with undefined. There is no type checking for parameter values: values of any type can be passed to any parameter.

  • The method invocation pattern
    When a function is saved as an attribute of an object, we call it a method. When a method is called,thisIs bound to the object. If the call expression contains an action that extracts an attribute (that is, contains a. expression of dot symbolor[subscript] subscript expression), then it is called as a method.

var myObject = {
  value :0;
    this.value += typeof inc ==='number'?inc:1;
  }The // increment method takes an optional parameter. If the parameter is not a number, the number 1 is used by default  
document.writeln(myObject.value);   // 1 

document.writeln(myObject.value);   // 3

Method can be usedthisTo access an object, you can modify it from the object.thisWhen every binding to an object occurs in a call, this super late binding function canthisHighly reusable. adoptthisThe way to get the context of the objects to which they belong is calledPublic method

  • The function invocation pattern

When a function is not an object property, it is called as a function:

Var sum = add (3, 4); // sum has a value of 7

When a function is called in this mode,thisBeing bound to a global object is an error in language design. WhenInternal functionWhen called,thisShould be bound toThis of external functionVariables. The solution is: if the method defines a variable and assigns it a value ofthis, the inner function can be accessed through that variablethis, by convention, namedthat

MyObject. Double = function() {// add a double method to MyObject
  Var that = this; // solution
  var helper = function() {
   that.value = add(that.value, that.value);  
  Helper(); // call helper as a function
MyObject. Double(); // call double as a method
document.writeln(myObject.Value());  //6
  • The constructor invocation pattern

JavaScript is a language based on prototype inheritance, which means that objects can inherit properties directly from other objects. This language has no category.
If a function is called with new in front of it, a new object will be created to hide the prototype member connected to the function, and this will be bound to that new object. The new prefix also changes the behavior of the return statement.

Var quo = function (string) {// create constructor function quo, object with status attribute
    this.status = string;
Quo. Prototype. Get UU status = function() {// provides a public method named get UU status
    return this.status;  
Var myquo = new quo ("configured"); // construct an instance of quo
Document. Wirteln (myquo. Get_status()); // print and display "configured"

Recommended Today

Opencv realizes image cutting function

Opencv implementation cuts the image into m * n blocks for your reference. The details are as follows 1、 Code part: #include “stdafx.h” #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <iostream> #include <vector> #include<string> #include<sstream> using namespace std; using namespace cv; //Cut an image into m*n patch void Cut_img(Mat src_img, int m, int n, vector<Mat> ceil_img) { […]