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

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