Deconstruction assignment
Deconstruction must be very well understood, no need to say more. Let’s start with a little 🌰
function foo(x,y,z){
console.log(x,y,z) } foo(... [1.2.3])
foo.apply(null[1.2.3])
Copy the code
Another case is… Another common use of “is basically the reverse behavior
function foo(x,y, ... z){
console.log(x,y,z)
}
foo(1.2.3.4.5) / / 1, 2, three, four, five
// Know why (... Args is often written like this
Copy the code
Deconstruction I prefer to call it collection: reset parameter
function foo(. args){
console.log(args)
}
/ / foo ([1, 2, 3, 4, 5,])
Copy the code
Here are some things to watch out for:
-
The reset/ Gather parameter cannot have default values
-
Function defaults can be any legal expression, function call
function bar(val) {
console.log('var called')
return y + val;
}
function foo(x = y + 3, z = bar(x)) {
console.log(x, z)
}
var y = 5;
foo();
foo(10);
y = 6
foo(undefined.10);
// undefined means missing
Copy the code
The default value expression is lazily evaluated when the parameter value is omitted or undefined
Formal parameters in a function declaration are in their own scope and can be understood as (…). , instead of the function lift scope, which means that identifier references in default value expressions are first matched to the formal parameter scope before the outer scope is searched.
var w = 1,
z = 2;
function foo(x = w + 1, y = x + 1, z = z + 1) {
console.log(x, y, z)
}
foo(); //ReferenceError
Copy the code
TDZ was introduced in ES6, which prevents variables from being accessed in an uninitialized state.
Default value expression
// Function reference, not function call itself
/ / foo structure
function foo2() {
return [1.2.3];
}
var tmp = foo2(),
a = tmp[0],
b = tmp[1],
c = tmp[2]
console.log(a, b, c)
Copy the code
You can think of manual assignment of indexed values in an array or object property as structured assignment. Change it to the following:
var {
a,
b,
c
} = foo2()
Copy the code
Note that you should not mix declarations in assignments, or you will get syntax errors.
var x = 10,
y = 20;
[y, x] = [x, y]
console.log(x, y)
Copy the code
The completion of an assignment expression for an object or array structure is the value of all the objects/arrays on the right.
var a = [2.3.4];
var b = [...a, c]
Copy the code
The structural parameters
function f3([x, t, ...z], ... w) {
console.log(x, y, z, w)
}
f3([]);
f3([1.2.3.4].5.6)
Copy the code
Destruct default + Parameter Default Function parameter default if it is an object, instead of destruct default. It only takes effect if the second argument is not passed, or if undefined is passed. Look at this example:
function test({ x = 1 } = {}, { y } = { y: 2 }) {
console.log(x, y);
}
test({}, {}); //1 undefined
test(); / / 1. 2
test(undefined.undefined) / / 1. 2
test({}, undefined) / / 1, 2
test({ x: 2 }, { y: 3 }) / / 2, 3
Copy the code
We pass in the argument ({}), so instead of using the default {y:10}, we construct {y} on the empty object {} we pass in
// Nested defaults
//default is merged into config
var defaultt = {
options: {
remove: 1.enable: 2,}} {// Destruct (with default value assignment)
let {
options: {
remove: default.options.remove,
enable: default.options.enable,
} = {},
log: {
warn = defalut.log.warn,
error = defalut.log.error
}
} = config;
/ / restructuring
config = {
options: {
remove,
enable
},
log: {
warn,
error
}
};
}
/ / generator
var o = {
* foo() {
}
}
// Deep understanding
runSomething({
something: function something(x, y) {
if (x > y) {
// Swap recursive calls to x and y
return something(y, x)
}
return y - x
}
})
Copy the code
The first property something allows us to pass o.soup (..) To call, like its public name. The second something is a lexical name that it uses to refer to the function internally, for the purpose of recursion.
// If we take the neat approach
runSomething({
something(x, y) {
if (x > y) {
// Swap recursive calls to x and y
return something(y, x)
}
return y - x
}
})
Copy the code
You will be prompted that the Someting identifier could not be found, and concise methods mean anonymous function expressions.
You should use them when you don’t need them to perform recursion or event binding/unbinding
var o = {
__id: 10,
get id() {
return this.__id++;
},
set id(v) {
return this.__id = v;
}
}
o.id;
o.id;
o.id = 20;
o.id;
o.__id;
o.__id;
Copy the code
Setter literals must have one and only one declaration parameter: omitting or overwriting is a syntax error.
The required parameters can be destructed and default values set id({id: v=0}){.. }
But gather/reset… Is not allowed set id(… v){.. }
Super is only allowed in compact methods, not in normal function expression properties, and only in super.xxx (for property/method access), not in super()
String literals are in the lexical scope in which they appear and do not have any kind of dynamic scope
function foo(string ,... value){
console.log('string: ', string);
console.log('... value: '. value); }var desc = 'awesome'
foo`Everything is ${desc}! `;
Copy the code
The tag section, i.e.. The string literal, as I said earlier, is the value of a function to call. In fact, it can be any expression that results in a function, or even a function call that results in another function
Arrow function
The arrow function is a new addition to ES6, so here’s how to use it.
Arrow function expressions have a much cleaner syntax than function expressions and don’t have their own this, arguments, super, or new.target. These function expressions are more suitable for places where anonymous functions are needed, and they cannot be used as constructors.
Arrow functions are always expressions, there are no arrow functions declared inside the arrow functions, and the this binding is not always dynamic, but syntactic. => is the lexical alternative to var self = this (or.bind(this)).
We said that arrow functions get their values from lexical ranges. This means that it just uses the value in the surrounding code block. It doesn’t care what it’s called, it only cares where it’s defined.
let obj = {
myVar: 'foo'.myFunc: function() {
console.log(this.myVar)
setTimeout((a)= > {
console.log(this.myVar)
}, 1000)
}
}
obj.myFunc() // foo ... then... foo
Copy the code
MyFunc’s this value depends on obj, so myFunc. MyVar can be successfully printed from foo. However, the second function is called by setTimeout, so its context is different. Its context is actually a timeout object in the node or a window object in the browser, so although we might still want it to point to OBj, we’ve lost the binding.
You might want this to point to obj. But arrow functions do not bind it to the object that calls them. They only use this value within the limits defined. In this case, this refers to the global object. So arrow functions cannot be used for object methods!
let a = {
foo: 1.bar: (a)= > console.log(this.foo)
}
a.bar() //undefined
Copy the code
The arrow function’s this does not refer to the object A. Object A does not constitute a scope, so it goes up to the global scope, and this points to the global scope.
A constructor
let Person = function(name, height) {
this.name = name
this.height = height
}
Person.prototype.hello = function() {
console.log('Hi, my name is ' + this.name)
}
let alice = new Person('Alice'.1.7)
alice.hello() // Hi, my name is Alice
Copy the code
argument
let sum = (. args) = > {
return args.reduce((a, b) = > a + b, 0)
}
sum(1.4.5) / / 10
Copy the code
tip
Omit {} and return If the body of the arrow function contains only one expression, you can omit the curly braces {} and return keyword. Don’t worry about omitting the return; arrow functions implicitly return expressions.
let funCon = who= > `${who}, hello`
funCon('wyqn')
Copy the code
You might have a situation where you want to return an object.
const funCon = who= > ({ message: `${who}, hello! ` });
funCon('wyqn'); // => { message: `wyqn, hello!` }
Copy the code
Timing rules for arrow functions:
-
Short sentence: return a value -> the function has no internal reference to this and no reference to itself (recursive, event binding/unbinding) -> does not execute other functions defined by the function expression
-
An inner function expression that can use the arrow function if it relies on calling var self = this (or.bind(this)) in the containing function.
-
Bottom line => are lexical bindings for this, arguments, and super.
Arrow functions do not apply timing rules:
- Do not define arrow functions in the outermost layer, because operating on this inside the function can easily contaminate the global scope. At the very least, wrap a normal function around the arrow function and keep this visible.
Afterword.
Welcome to follow the wechat public account! For better communication.Copy the code