(五)ES6字符串模板箭头函数字面量

2018-06-12  本文已影响0人  我拥抱着我的未来

本节知识点

字符串模板

    let a = "今天天气真好啊";
    let str = `<h1>33333</h1><p>${a}</p>`;
    document.getElementById("div1").innerHTML = str;

箭头函数

//老版本
function abc(num) {
    return num * 2;
}
console.log(abc(2));
//新版本
let a = (num) => num * 2;
console.log(a(2));
//要是有多个语句怎不能不写括号了
let b = (num) => {
    let sum = num * 2;
    return sum;
}
console.log(b(2));
(2)改变this指针

箭头函数中的this找的是他父元素的上一级,切记切记!!!

var x = 11;
var obj = {
    x: 22,
    say: function() {
        console.log(this.x)
    }
}
obj.say();
//console.log输出的是22

var x2 = 11;
var obj2 = {
    x2: 22,
    say: () => {
        console.log(this.x2);
    }
}
obj2.say();
//输出的值为11

字面量

function createBookShop(obj2) {
    return {
        obj2: obj2,
        inventoryValue: function() {
            return this.obj2.reduce(function(total, book) {
                return total + book.price
            }, 0)
        },
        priceForTitle: function() {
            return this.obj2.find(function(item, index) {
                return item.price > 10
            })
        }

    }

}

const obj2 = [
    { title: "value", price: 10 },
    { title: "Angular", price: 15 }
];
const bookShop = createBookShop(obj2);
console.log(bookShop.priceForTitle());
console.log(bookShop.inventoryValue());
function createBookShop(obj2) {
    return {
        obj2,
        inventoryValue() {
            return this.obj2.reduce(function(total, book) {
                return total + book.price
            }, 0)
        },
        priceForTitle() {
            return this.obj2.find(function(item, index) {
                return item.price > 10
            })
        }

    }

}

const obj2 = [
    { title: "value", price: 10 },
    { title: "Angular", price: 15 }
];
const bookShop = createBookShop(obj2);
console.log(bookShop.priceForTitle());
console.log(bookShop.inventoryValue());
上一篇下一篇

猜你喜欢

热点阅读