普通函数
this: this代表当前正在执行的对象
普通函数 this: this 代表当前正在执行的对象 对象.函数( this === 对象 )
箭头函数
箭头函数: 箭头函数 没有自己的 this, 箭头函数的 this 是在他 "定义的时候" 就 "固定不变了", 会去寻找上一级作用域的 this 当成自己的
如果没有参数,就直接写一个空括号即可
如果只有一个参数,可以省略小括号
如果有多个参数,用逗号分割
如果函数体的返回值只有一句,可以省略大括号
只有一条语句 默认带 return
箭头函数没有自己的this 箭头函数的this 是在箭头函数 "定义的时候" 就固定不变了 会去上一级作用域链去找 this
var user = '小花'
const obj = {
user: '小白',
fun: () => {
// window
console.log(this.user, 2);
},
}
// this === window
const fun = () => {
// this === window
console.log(this.user);
}
function person () {
// this === window 锁死
const xxx = () => {
// this === window
console.log(this.user);
}
// this === person
xxx()
// this ===
xxx.call(obj)
}
// window.person
person()
// this === window
// 小花
fun()
// obj
// window
// 小花
fun.call(obj)
const xxx = obj.fun
// this === obj
xxx()
WebSocket
WebSocket是一种在单个TCP连接上进行全双工通信的协议。WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据
1. WebSocket 是一个长链接
2. 用法是 new WebSocket(ws:// wss://)
3. WebSocket 有4个监听事件 2个方法,
new WebSocket
const ws = ref.current = new WebSocket('ws://localhost:8181')
// onopen 连接建立时触发
ws.addEventListener('open', () => {
console.log('创建成功了');
})
// onmessage 客户端接收服务端数据时触发
ws.addEventListener('message', opt => {
console.log(opt.data, 'opt.data');
})
// onerror 通信发生错误时触发
ws.addEventListener('error', error => {
})
// onclose 连接关闭时触发
ws.addEventListener('close', opt => {
})
WebSocket方法
Socket.send():向服务器发送数据
Socket.close():关闭连接