javascript essence of language study notes

Re-read the previous study notes left behind, found it a curried just remember the concept.

And the content of the book is really old, read warp, so a lot of Riga below Ps.

------ Update March 2020

The first chapter essence

Javascript is built on some very good ideas and a few very bad idea,

Object literal excellent ideas include functions, weakly typed, dynamic objects and expressive representation.

Those bad ideas include a programming model based on global variables.

The second chapter grammar

digital:

javascript only a numeric type, is internally represented as 64-bit floating-point number. Infinity represents all values ​​greater than the 1.79769313486231570e + 308.

NaN represents a value not produce a normal result, NaN is not equal to any value, including itself. The function can be used isNaN ES5 (number) detected NaN.

Ps. To ES 10, JS has been the second number representing the type, BigInt

Statement:

Value is determined as false by the following: false, null, undefined, empty string '', the number 0, number NaN.

Ps. ES design criteria described functions refer directly ToBoolean

The third chapter Object

Javascript simple data types include numeric, string, boolean, null value and undefined value. All other values ​​are objects.

Numbers, strings, Boolean "looks like" objects because they have the means, but they are immutable.

In Javascript arrays are objects, functions are objects, the regular expression is an object, of course, natural objects are objects.

Ps. ES6 Added Symbol type, ES10 add new BigInt type, so simple data types There are seven kinds

Parameters passed - passed by value and reference transmission

Object passed by reference, they will never be replicated. Base-type passed by value

function add(num){  
   num+=10;  
   return num;  
}  
num=10;  
alert(add(num));  
aelrt(num);  
//输出20,10 

The output 20, 10 here, the official explanation is that when the JS basic types of parameter passing, a copy made num stack frame copy operation, so that the external variable declarations and function parameters num, have exactly the same value , but with a completely different parameter addresses, both of whom did not know who, when the function call returns a pop-up function parameter num stack frame.

So change the function parameters num, with no impact on existing external variables.

function setName(obj){  
    obj.name="ted";  
    obj=new Object();  
    obj.name="marry";  
}  
var obj=new Object();  
setName(obj);  
alert(obj.name);  
//输出ted 

setName function obj incoming address, so the second line of approach, line 6 of obj affected. But the first line of the address obj 3 practices within the function is changed to the new stack space, please see this article

Ps. Passed by value and reference pass something commonplace Bale

enumerate

Object uses for in the enumeration loop, if it is necessary to filter out unwanted values. The most common filters are hasOwnProperty method or to exclude the function of typeof.

var stooge = {
    'first-name': 'Jerome',
    'last-name': 'Howard'
}
for (var name in stooge) {
    if (typeof stooge[name] !== 'function') {
        console.log(name + ': ' + stooge[name]);
    }
}

Array using a for loop, which can traverse in the correct order, and do not worry about the prototype chain enumerated attributes.

Enumeration Ps. I personally prefer Object.keys (obj) .forEach (index => {}) of the method object do

delete

delete operator can be used to delete the object's properties. If the object contains the property, then the property will be removed. He will not touch any object prototype chain.

Properties deleted objects may make from prototype chain through stand out

stooge.__proto__.nickname = 'Curly';
stooge.nickname = 'Moe';

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

Ps. Delete caution, to use it only to delete properties on objects, do not delete other things. And strict and non-strict mode will be different. See MND-delete operator

Chapter IV Functions

transfer

In Javascript call There are 4 modes: method call mode, the function call mode, the call mode is configured, Apply call mode. These calls are different models on how to initialize the key parameters of this.

Method call mode: You can use this to access the object they belong.
var myObject = {
    value: 0,
    increment: function(inc){
        this.value += typeof inc === 'number' ? inc : 1;
    }
};
myObject.increment();
console.log(myObject.value); // 1
 
myObject.increment(2);
console.log(myObject.value); // 3
Function call mode: this mode this is bound to the global object.
var someFn = function () {
    return this === window; //true
}
Constructor calls mode

In front bring a new function to call, then secretly creates a connection to the new object prototype member of the function. At the same time this will be bound to the new object.

var Quo = function (string) {
    this.status = string;
}
Quo.prototype.get_status = function(){
    return this.status;
}
var myQuo = new Quo('confused');
console.log(myQuo.get_status()); //'confused'
apply call mode: let's build an array of parameters passed to the calling function that allows us to select the value of this.
var statusObject = {
    status: 'A-OK'
};
var status = Quo.prototype.get_status.apply(statusObject);

(call, apply, bind distinction see here) [ http://blog.itpub.net/29592957/viewspace-1159067/ ]

var xw = {
    name : "小王",
    gender : "男",
    age : 24,
    say : function(school,grade) {
            alert(this.name + " , " + this.gender + " ,今年" + this.age + " ,在" + school + "上" + grade);                                
    }
}
var xh = {
    name : "小红",
    gender : "女",
    age : 18
}
 
//对于call来说是这样的
xw.say.call(xh,"实验小学","六年级");       
//而对于apply来说是这样的
xw.say.apply(xh,["实验小学","六年级郑州牛皮癣医院"]);
//看到区别了吗,call后面的参数与say方法中是一一对应的,而apply的第二个参数是一个数组,数组中的元素是和say方法中一一对应的,这就是两者最大的区别。
//那么bind怎么传参呢?它可以像call那样传参。
xw.say.bind(xh,"实验小学","六年级")();
//但是由于bind返回的仍然是一个函数,所以我们还可以在调用的时候再进行传参。
xw.say.bind(xh)("实验小学","六年级");

Ps. 2020 years, we react so much to write, bind function like known to everybody afraid of it

parameter

When the function is called, you will get a free distribution parameter is an array of arguments. Error on a design language, arguments is not a true array, it's just an object "array-like" of. Although it has a length property, but there is no way any of the array. To use an array of methods need to use call functions.

var sum = function () {
    var i, sum = 0;
    for (i = 0; i < arguments.length; i += 1) {
        sum += arguments[i];
    }
    return sum;
};
sum(4, 8, 15, 16, 23, 42); //108

return

A function always returns a value. If you do not specify a return value, it returns undefined.
If the function call preceded the new prefix, and the return value is not an object, the this (the new object) is returned

abnormal

If the processing means depends on the type of exception, the exception handler must check the attribute name of the exception object to determine the type of abnormality.

var add = function(a, b) {
    if (typeof a !== 'number' || typeof b !== 'number') {
        throw {
            name: 'TypeError',
            message: 'add needs numbers'
        };
        return a + b;
    }
}
 
//构造一个try_it函数,以不正确的方式调用之前的add函数
var try_it = function(){
    try{
        add('seven');
    } catch(e) {
        console.log(e.name + ': ' + e.message);
    }
}
 
try_it();

Scope

javascript code does not support the block-level scope, only function scope. Many modern languages ​​are recommended delay declare variables as possible. And used on javascript then it will become bad advice,

Because it lacks block-level scope. The best practice is to declare all variables at the top of the function of the function body that might be used.

Ps. Cancer, but ES6 has launched let you declare a variable, so the book said this situation is not a problem.

Closure

Closure is the function of the internal functions, reference can be defined in a variable acting on the outside thereof. Closures than creating their functions have a longer life cycle, and the closure is a reference to its internal memory external variables.

function box(){
    var val = undefined;
    return {
        set: function(newVal) { val = newVal; },
        get: function() { return val; },
        type: function() { return typeof val; }
    };
}
var b = box();
b.type(); //"undefined"
b.set(98.6);
b.get(); //98.6
b.type(); //"number"

Understand the difference between assignment and binding.

Closure by reference instead of the captured value of their external variables.

Use function expression (IIFE) immediately call to create a local scope.

Look for a program BUG:

function wrapElements(a) {
    var result = [];
    for(var i = 0, n = a.length; i < n; i++) {
        result[i] = function() { return a[i]; };
    }
    return result;
}
var wrapped = wrapElements([10, 20, 30, 40, 50]);
var f = wrapped[0];
f(); //undefined

This code is deceptive, this programmer may wish to program 10 output, but the output value is undefined.

This is because function() { return a[i]; };of this closed storage bag i i is the address of the external variables, each time for the cycle continues, a new closure, i values are updated. So i always get the value of i value after the end of the for loop.

Correct word should go to create a function called immediately

function wrapElements(a) {
    var result = [];
    for(var i = 0, n = a.length; i < n; i++){
        (function(j){
            result[i] = function() {return a[j];};
 
        })(i);
    }
    return result;
}

Ps. The old routine, but rather abruptly when you do write cycle asynchronous operation or perineum to you.

Module

Using the function module and closure configuration, it may provide an interface module is a function or an object is hidden state. By modules, we can almost completely abandon the use of global variables.

cascade

If we allow this method returns rather than undefined, you can enable cascade (chain programming)

getElement('myBoxDiv')
    .move(350, 150)
    .width(100)
    .height(100)
    .color('red');

Function currying

Is also a function value, we can operate in a manner went function values, currying allows us to function in conjunction with the parameters passed to it, to produce a new function.

Compatible with modern browsers and IE browser add event method:

var addEvent = (function(){
    if (window.addEventListener) {
        return function(el, sType, fn, capture) {
            el.addEventListener(sType, function(e) {
                fn.call(el, e);
            }, (capture));
        };
    } else if (window.attachEvent) {
        return function(el, sType, fn, capture) {
            el.attachEvent("on" + sType, function(e) {
                fn.call(el, e);
            });
        };
    }
})();

To do so would only need to determine once and do not have to judge each call addEvent Code of ie6 7 8. This is typical of currying

Performing an initial value actually achieved addEvent Application Part (only once if ... else if ... determination), whereas the remaining parameters are applied to achieve the function returns, typically currying.

Ps. Read so many times curried, although that is such a thing, but always quickly forgotten his name.

Chapter V inheritance

Pseudo-classes

//定义一个构造器,并扩充它的原型
var Mammal = function (name) {
    this.name = name;
};
Mammal.prototype.get_name = function(){
    return this.name;
};
Mammal.prototype.says = function () {
    return this.saying || '';
};
 
//构造伪类去继承Mammal,替换它的prototype为一个Mammal的实例来实现
var Cat = function(name) {
    this.name = name;
    this.saying = 'meow';
};
Cat.prototype = new Mammal();
//扩充新原型对象
Cat.prototype.get_name = function () {
    return this.says() + ' ' + this.name + ' ' + this.says();
};
//创建实例
var myCat = new Cat('Henrietta');
myCat.says(); //'meow'
myCat.purr(5); //'r-r-r-r-r'
myCat.get_name(); //'meow Henrietta meow'

Many shortcomings pseudo-classes, such as no private environment, all properties are public; can not access the parent class. To make matters worse, create an instance when forget to add new prefix, the inside of this constructor will be bound to the window object, thereby undermining the global environment variables.

Ps. ES6 write directly to Class provincial thing now, but there is always fear the interviewer will ask how to do, and that was a direct reference to my other ES5 inherit the optimal solution

Function of

One weakness inheritance pattern is not privacy, property of the object are visible, you can use application modules mode to solve.

var mammal = function (spec) {
    var that = {};
 
    that.get_name = function() {
        return spec.name;
    };
    that.says = function() {
        return spec.saying || '';
    };
 
    return that;
};
var myMammal = mammal({name: Herb});
 
var cat = function(spec){
    spec.saying = spec.saying || 'meow';
    var that = mammal(spec);
    that.get_name = function(){
        return that.says() + '' + spec.name + ' ' + that.says();
    };
    return that;
};
 
var myCat = cat({name: 'Henrietta'});
 
//定义一个处理父类的方法的方法
Function.prototype.method=function(name, func){  
    this.prototype[name]=func;  
    return this;  
} 
Object.method('superior', function(name){
    var that = this,
        method = that[name];
    return function(){
        return method.apply(that, arguments);
    };
});
 
var coolcat = function(spec){
    var that = cat(spec),
        super_get_name = that.superior('get_name');
    that.get_name = function(n){
     
        //调用父类方法
        return 'like ' + super_get_name() + ' baby';
    };
    return that;
};
var myCoolcat = coolcat({name: 'Bix'});
var name = myCoolCat.get_name(); // 'like meow Bix meow baby'

Compared pseudo-class mode, using the function model can then get better encapsulation and information hiding, and the ability to access the parent class

Chapter VI Array

Confusing place

js difference for arrays and objects are confusing. Type typeof operator report of the array is 'object' makes no sense.

We can make up for this deficiency by custom function is_array

var is_array = function(value) {
    return value && 
        typeof value === 'object' && 
        value.constructor === Array;
};

Unfortunately, the number of which is configured in an array identified from different windows (window) or frame (Frame) fails when inside. There is a better way to judge

var is_array = function (value) {
    return Object.prototype.toString.call(value) === '[object Array]';
}

Ps. Refer also to identify the type of direct me another one

Chapter VII Regular Expressions

Regularization factor

In addition, except the following control characters and special characters, all characters are processed literally

\ / [ ] ( ) { } ? + | . ^ $ -

If you need listed above to match the character literally, you need to use a \prefix to escape

As a not escaped. Will match any character except \ n, other than

Regex escape character

  • \ F is feed character, \ n newline, \ r is a carriage return, \ t tab
  • \ D is equivalent to [0-9], which matches a number. \ D In contrast, non-matching number, [^ 0-9]
  • \ S Matches any whitespace characters, including spaces, tabs, page breaks, and so on. It is equivalent to [\ f \ n \ r \ t \ v]. \ S contrary
  • \ W matches any word character including underscore. It is equivalent to the "[A-Za-z0-9_]". \ W contrast
  • \ B matches a word boundary, that is, refers to the location and spaces between words. For example, "er \ b" matches "never" in the "er", but does not match the "verb" in "er".

Ps. Regular please refer to Issue

Chapter VIII Methods

Ps. Too much trouble, and now directly see MDN get away

Appendix A, JS cancer

  • Global variables: JS programming code is based on a global variable, the global variable is the devil. Large-scale program will be very difficult to maintain global variables, and implicit global variables will become very difficult bug to find.
  • Scope: JS code does not block-level scope, only function scope.
  • null is not an object. Explanation: While typeof null will output object, but this is only the existence of a long JS Bug. JS used in the original version of the system is 32-bit, to consider the type of information to use low performance storage variable, however, the object 000 is representative of the beginning of an all-zero or null, the error is determined it to object.
  • Automatically inserted semicolon: automatic insertion of semicolon may mask a more serious mistake. The following program error is automatically inserted into a semicolon it returns undefined, without any warning, the solution is to write braces after the return statement
//错误实例
return
{
    status: true;
};
//正确做法
return {
    status: true;
};
  • Reserved word: this word is retained in a similar class byte js, the name can not be used for variables or parameters, and most of these words and language is no longer in use.
  • Coding problem: js beginning of the design, is expected to 65536 Unicode characters, js character is 16 bits, enough to cover the original 65536, is now slowly increase to 100W Unicode characters.
    The remaining one million characters each of which can be represented by a pair of characters. A pair of Unicode character as a single character, and js think a pair of character are two different characters.
  • typeof: typeof operator does not identify null and objects. typeof regular expression on the type identification, each browser implementations less consistent, IE / FF / opera return 'object', Safari 3.x Versions Back 'function', 5.x version of 'Object'
    typeof operator a indistinguishable arrays and objects.
  • +: Connection string, you can perform addition, this complex behavior is a common source of the bug. If you plan to do an addition operation, make sure that both operators are integers.
  • Float: js 0.1 + 0.2 is not equal to 0.3, but the floating-point integer arithmetic is accurate, so it is best capable of decimal places into integer arithmetic, and then converted to decimal.
  • Pseudo-array: js no real array, js array of really useful, do not have to set up cross-border dimension and will never produce an error, but the performance and the true array than Mom. typeof operator not is also checked arrays and objects, respectively. We need the help of other functions
  • False value: 0, NaN, '' (the empty string), false, null, undefined. It is false logic value of js determined. If you are using == judgment, it is easy to get unexpected results

Appendix B, JS dross

  • And === ==: == operator forces operand data type conversion, the conversion rule complex strange, to be used for determining recommendations === symbol.
  • with the statement: results will be unpredictable, but also seriously affect js processing speed avoided.
  • eval: eval form code more difficult to read, so that performance decreased significantly, because it needs to run the compiler, testing tools for testing the ability to make JSlint like greatly reduced; also weaken the security of the program.

Function constructor is also another form of eval, should be avoided. Similarly serTimeout setInterval function and can accept a string parameter and the function argument, when the parameter string, as will eval
as to process, which avoid the use of a string argument.

  • continue: continue statement jumps to the top of the cycle. But the decline in performance, be avoided.
  • switch through: case conditions down through to another case conditions, that is, through the switch. This is a common source of error, and it is difficult to find errors by looking at the code. Avoid using cross.
  • Bit Operators: js and there is no integer type, use bitwise first converted to an integer, and then to perform the operation, so the execution speed is very slow. js performs less bit operator, using the bit operator makes easier bug hidden.
  • Contrast function expression function statement: function is recommended to use the expression, because it made it clear that foo is a variable that contains the function value. Good understanding of the language, understand the value function is very important.
var foo = function () {};

function to enhance the scope statement occurs when parsing, so do not go in there if the function statement

  • Wrapper object type: for example, new Boolean (false); returns an object, object type, will cause some problems when typeof operator judgment. So avoid using new Boolean, new Number, new String.
  • Also avoiding the use of new Object, new Array written, use and instead {} [].

  • new operator: If you missed the new operator, the constructor is called when this tied to the global object, with very serious consequences.
  • void: many languages, void is a type that represents no value. In js li, void is an operator that takes a number of operational and returns undefined. This is not what should be avoided it. Forehead, he said that, but I still would like to use void 0 to get the undefined value.

Appendix E, JSON

json object into another string format conversion, the code below the

var str = JSON.stringify({what:'sss'})   //"{"what":"sss"}"
JSON.parse(str)  // Object {what: "sss"}

A JSON parser, see another article JSON parser

Guess you like

Origin www.cnblogs.com/everlose/p/12501471.html