ES6部分方法点评(二)

本文首发于Array_Huang的技术博客——实用至上,非经作者同意,请勿转载。
原文地址:https://segmentfault.com/a/1190000005046177

template string

template string(模板字符串),至ES6,javascript终于也能直接往字符串里插变量了。这用途嘛,说大不大,说小也不小;虽说不能实现比较复杂的例如if/for等语句就不能说是一个完整的模板引擎,但起码以后拼字符串就不用老写连接符+了不是?

let name = 'guoyongfeng';
let age = 18;

console.log(`${name} want to drink ${age}`)

Default(函数默认参数)

喜大普奔!javascript终于能像其它语言一样在语言层面给形参设默认值了:

function f(x, y=12) {
  // y is 12 if not passed (or passed as undefined)
  return x + y;
}
f(3) == 15

class, extends, super

作为一个从PHP起跑的码农,这仨语法糖我真的是不得不吃。一直以来,javascript的面向对象一般都是靠prototype,但毕竟跟其它语言中的class还是相差甚远的(当然硬要实现class也行,就是特麻烦),现在ES6终于从语言层面实现class了,鼓掌!!

class Animal {
    constructor(){
        this.type = 'animal'
    }
    says(say){
        console.log(this.type + ' says ' + say)
    }
}

let animal = new Animal()
animal.says('hello') //animal says hello

class Cat extends Animal {
    constructor(){
        super()
        this.type = 'cat'
    }
}

let cat = new Cat()
cat.says('hello') //cat says hello

Object.assign

这实际上就是jquery/zepto提供的extend方法,即把多个object合并到一起,这下又多了一个抛弃jquery/zepto的理由了:

var target = { a: 1 };

var source1 = { b: 2 };
var source2 = { c: 3 };

Object.assign(target, source1, source2);
console.log(target); // {a:1, b:2, c:3}

本文首发于Array_Huang的技术博客——实用至上,非经作者同意,请勿转载。
原文地址:https://segmentfault.com/a/1190000005046177

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章