欢迎来到DIVCSS5查找CSS资料与学习DIV CSS布局技术!
简化对象写法
 
ES6 允许在大括号里面,直接写入变量和函数,作为对象的属性和方法,这样更简介。
 
在ES5中创建对象的写法:
 
let name = "江流儿"
 
let showName = function(){
 
    console.log("name:",this.name);
 
}
 
const People = {
 
    name: name,
 
    showName: showName,
 
    func: function(){
 
        console.log("正在西游的路上!");
 
    }
 
}
 
console.log(People);
 
在ES6中创建对象的写法:
 
let name = "江流儿"
 
let showName = function(){
 
    console.log("name:",this.name);
 
}
 
const people = {
 
    name,//省略了重复的工作
 
    showName,
 
    func(){
 
        console.log("正在西游的路上!");
 
    }
 
}
 
console.log(people);
 
箭头函数及声明特点
 
ES6 允许使用箭头=>定义函数
 
申明一个函数
 
在ES5中创建函数的写法:
 
let fn = function(a, b){
 
…//代码体
 
}
 
在ES6中创建函数的写法:
 
let fn = (a, b) => {
 
…//代码体
 
}
 
箭头函数特点
 
this 是静态的,this始终指向函数声明时所在作用域下的 this 的值,即使使用call、apply、bind函数修改this,也不会起作用。
 
//ES5写法
 
function getName1() {
 
    console.log("ES5:",this);
 
};
 
//ES6写法
 
let getName2 = () => {
 
    console.log("ES6:",this);
 
};
 
const people = {
 
    name: "江流儿"
 
};
 
getName1.call(people);//people
 
getName2.call(people);//window
 
不能作为构造函数实例化对象
 
let Person = (name, age) => {
 
    this.name = name;
 
    this.age = age;
 
}
 
let stu = new Person("心猿", 5000);
 
console.log(stu);//err
 
不能使用arguments变量
 
let fn =() =>{
 
    console.log(arguments);
 
}
 
fn(1, 2, 3);//err
 
箭头函数的简写
 
1)省略小括号,当形参有且只有一个的时候
 
let add = n =>{
 
    return n+n;
 
}
 
console.log(add(9));//18
 
2)省略花括号,当代码体只有一条语句的时候,此时的return必须省略,语句的执行结果就是函数的返回值
 
let pow = n => n * n;
 
console.log(pow(9));//81
 
箭头函数的实践
 
1)点击div 2s 后颜色变成粉色
 
在ES5中写法:
 
    <style>
 
        div{
 
            width: 200px;
 
            height: 200px;
 
            background-color: #58a;
 
        }
 
    </style>
 
<body>
 
    <div id="box"></div>
 
    <script>
 
        let div = document.getElementById("box");
 
        box.addEventListener("click", function(){
 
            // ES5中必须先保存this的值
 
            let _this = this;
 
            // 定时器
 
            setTimeout(function(){
 
                // 修改背景颜色 this
 
                _this.style.background = "pink"
 
            }, 2000);
 
        })
 
    </script>
 
在ES6中使用箭头函数写法:
 
    <script>
 
        let div = document.getElementById("box");
 
        box.addEventListener("click", function(){
 
            // 保存this的值
 
            // let _this = this;
 
            // 定时器
 
            setTimeout(()=>{
 
                // 修改背景颜色 this
 
                // _this.style.background = "pink"
 
                this.style.background = "pink";
 
            }, 2000);
 
        })
 
    </script>
 
2)从数组中返回偶数的元素
 
const arr = [1, 6, 9, 10, 14, 200];
 
const result = arr.filter(item => item % 2 === 0);
 
console.log(result);//[ 6, 10, 14, 200 ]
 
箭头函数适合于this无关的回调。定时器,数组的方法回调
 
箭头函数不太适合与this有关的回调。例如事件回调,对象的方法

如需转载,请注明文章出处和来源网址:http://www.divcss5.com/html/h64196.shtml