es6学习总结 (this,Promise)
this指向问题
es5中一句话可有概括谁调用this就指向谁(运行时生效),es6中箭头函数中没有this,所以es6中的this相当于一个变量,她永远继承外层作用域的this(定义时生效),需要注意的对象不构成作用域,当然函数在生效时才能行车作用域。
-
function f(){
-
this.s1=18;
-
this.s2=19;
-
setInterval(()=>this.s1++,1000);
-
setInterval(function func(){
-
this.s2++
-
},1000)
-
-
}
-
var obj=new f()
-
setTimeout(()=>{console.log("s1:",obj.s1)},3000)
-
setTimeout(()=>{console.log("s2:",obj.s2)},3000)
-
-
//21
-
//19 借鉴官网的例子
promise的链式调用
-
function china(){
-
console.log('china中国')
-
var p =new Promise(
-
function( resolve,reject ) {
-
setTimeout(function(){
-
// console.log('中国 国家')
-
resolve('教育大省份')
-
},1000)
-
}
-
)
-
return p;
-
}
-
-
function jiangshu(data){
-
console.log('江苏'+data);
-
var p=new Promise(function(resolve,reject){
-
setTimeout(function (){
-
// console.log('江苏 省份')
-
resolve('地级市');
-
},2000)
-
})
-
return p;
-
}
-
-
function xian(data){
-
console.log('盱眙县'+data)
-
var p=new Promise(function(resolve,reject){
-
setTimeout(function(){
-
// console.log('盱眙县');
-
resolve ('淮河镇')
-
},2000)
-
})
-
return p;
-
}
-
china ().then(jiangshu).then(xian).then(function(data){
-
console.log(data)
-
})
-
-
//china中国
-
//Promise {<pending>}
-
//江苏教育大省份
-
//盱眙县地级市
-
//淮河镇
如上代码所示,promise的链式调用很好的避免的函数的回调地狱问题。
数组扩展运算符
作用将一个数组转为用逗号分隔的参数序列。
运算
-
var add=(a,c)=>a+c;
-
var Arr=[1,3];
-
add(...Arr)
-
//4
替代apply方法(只是相对数组用调用其它方法来说,因为apply的第二个参数正好是一个数组,因为apply本来是改变函数的this指向(箭头函数除外)),这是扩展运算符相当于数组的遍历看的很清楚。
-
var arr1 = [0, 1, 2];
-
var arr2 = [3, 4, 5];
-
Array.prototype.push.apply(arr1, arr2);
-
console.log(arr1)
-
// [0, 1, 2, 3, 4, 5]
-
-
-
let arr3=[1,2,3];
-
let arr4=[4,5,6];
-
arr3.push(...arr4)
-
console.log(arr3)
-
// [1, 2, 3, 4, 5, 6]
数组的浅拷贝
-
const a1 = [1, 2];
-
const a2 = [...a1];
将字符串转为数组
-
[...'hello']
-
// [ "h", "e", "l", "l", "o" ]
rest参数
arguments类数组通过Array.prototype.slice.call()转化为数组
-
function f(){
-
console.log(arguments)
-
let a=Array.prototype.slice.call(arguments,0)
-
console.log(a)
-
}
-
f(1,2,3,4)
-
// Arguments(4) [1, 2, 3, 4, callee: ƒ, Symbol(Symbol.iterator): ƒ]
-
// [1, 2, 3, 4]
-
es6通过rest参数去掉arguments参数,rest直接是个数组
-
const numbers = (...nums) => nums;
-
-
numbers(1, 2, 3, 4, 5)
-
-
//[1,2,3,4,5]
对象
ES6 引入了跟Object.keys配套的Object.values和Object.entries,作为遍历一个对象的补充手段,供for...of循环使用。
-
let {keys, values, entries} = Object;
-
let obj = { a: 1, b: 2, c: 3 };
-
-
for (let key of keys(obj)) {
-
console.log(key); // 'a', 'b', 'c'
-
}
-
-
for (let value of values(obj)) {
-
console.log(value); // 1, 2, 3
-
}
-
-
for (let [key, value] of entries(obj)) {
-
console.log([key, value]); // ['a', 1], ['b', 2], ['c', 3]
-
}
map数据结构(类似对象,值-值的对应,后续补充)
set数据结构(类似数组,没有重复元素)
看一个例子,数组去重的简单写法
-
let arr = [1,2,3,4,5,5,4,3,2,1];
-
let quchong= [...new Set(arr)];
-
console.log(quchong); // [1,2,3,4,5]
-
-
[...new Set('ababbc')].join('') //字符串去重
浙公网安备 33010602011771号