node.js设计模式(第二版) 第一章总结
1.let const
let块级作用域
'use strict'
if(true){
let a = 1;
}
console.log(a);//报错a没有定义
const定义的变量不能被修改
const a = 1;
a = 2; //报错Uncaught TypeError: Assignment to constant variable.
const定义对象,不能改变引用对象,可以改变引用对象内容
const a = {};
a.b = 1;//不会报错
a = null;//会报错
如果想定义不可更改的变量,可以使用Object.freeze()
const与let定义的变量不可以重名
var a;
const a;//报错
let a;//报错
2.箭头函数
特点:简单、箭头函数与父亲块级作用域相同
1.不使用箭头函数
function delayFunction(name){
this.name = name;
}
delayFunction.prototype.delay = function(){
setTimeout(function(){
console.log('hello' + this.name);
},500)
}
var b = new delayFunction('world');
b.delay()//输出hello
此时this指向全局
2.使用箭头函数
function delayFunction(name){
this.name = name;
}
delayFunction.prototype.delay = function(){
setTimeout(()=>{
console.log('hello' + this.name);
},500)
}
var b = new delayFunction('world');
b.delay()//输出hello
箭头函数为父亲块级作用域,this指向b
3.类class
class Person{
constructor(preName,name,age){
this.preName = preName;
this.name = name;
this.age = age;
}
fullName(){
return this.preName + this.name;
}
}
class Police extends Person{
constructor(preName,name,age,phone){
super(preName,name,age);
this.phone = phone;
}
fullInformation(){
return this.preName + this.name + this.phone;
}
}
4.key计算属性
const name = '--webkit--'
const style = {
[namespace + 'height'] : '300px',
}
5.新定义的getter与setter方法
var person = {
name: 'fa',
preName: 'dai',
get fullname(){
return this.preName + this.name;
},
set fullname(fullname){
let parts = fullname.split(' ');
this.preName = parts[0];
this.name = parts[1];
}
}
console.log(person.fullname);//daifa
console.log(person.fullname = 'ling jia');//lingjia
console.log(person.name);//ling
5.Map与Set
-
Map
Map相对于Object类型
Map拥有get,set,has,delete,size
Map通过set定义属性,Object一般直接定义
Map通过has可以判断是否拥有属性,Object一般使用hasOwnProperty或in
Map通过get获取属性对应的值,Object直接访问属性
Map通过size获取长度,数组通过length
Map遍历通过for…of…,对象一般使用for…in…
Map最终要可以用function与object当作key,可以用来存储测试函数与结果 -
Set
定义不重复的集合,方法有:add(添加项)、size(集合长度)、delete(删除项)、has(是否拥有项)
WeakMap与WeakSet主要是Map与Set的简化版本,不能遍历,只能用object当作key
特点
let obj = {};
const map = new WeakMap();
map.set(obj,{key: ‘value’});
console.log(map.get(obj));//{key:’value’}
obj = undefined;//map中的obj项自动被垃圾回收
NodeJS的非阻塞I/O
基于js中的发布者/订阅者思想实现
当需要I/O时,不会阻塞而发布一个事件,从而继续执行执行栈中代码,当I/O完成时触发事件从而触发对应的回调handler,handler进入执行栈执行。