React-Native开发从入门到实战项目总结ES5与ES6常用语法总结ES6

es5与es6常用语法教程(6)

2017-11-08  本文已影响152人  光强_上海

js常用语法系列教程如下

本节教程主要讲解以下几个常用语法

class类的创建

class Chef {
  // constructor
  constructor(food) {
    this.food = food
  }
  // 添加一个自定义的方法
  cook() {
    console.log(this.food)
  }
}

// 创建一个实例
let wanghao = new Chef('西红柿')
wanghao.cook()

迭代器(iterators)

function chef(foods) {
  let i = 0
  return {
    next() {
      // 定义一个bool变量,是否结束炒菜
      let done = (i >= foods.length)
      // 待抄的菜名
      let value = !done ? foods[i++] : undefined
      // 每一次执行next()函数会返回一个对象,对象中有两个属性,value表示抄的菜,done表示还有没有可以迭代的东西,没有了done的值就为true,就是完成了迭代
      return Boolean(done) ? '迭代完成' : {
        value : value,
        done : done
      }
    }
  }
}

// 返回一个厨子对象,厨子迭代炒菜。
let xiaoming = chef(['回锅肉', '糖醋里脊'])

// xiaoming这个厨子对象调用next() 函数
console.log(xiaoming.next())
console.log(xiaoming.next())
console.log(xiaoming.next())

生成迭代器(generators)

定义一个不传参数的生成器

// 这就是一个简单的生成器
function * chef() {
  yield '小炒肉'
  yield '麻婆豆腐'
  yield '红烧鲤鱼'
}

let wanghao = chef()
console.log (wanghao.next()) // {value: "小炒肉", done: false}
console.log (wanghao.next()) // {value: "麻婆豆腐", done: false}
console.log (wanghao.next()) // {value: "红烧鲤鱼", done: false}

定义一个可以传参数的生成器

function * chef(foods) {
    for(let i = 0; i < foods.length; i++) {
        yield foods[i]
    }
 }

let xiaoming = chef(['小炒肉', '麻婆豆腐', '红烧鲤鱼'])
console.log (xiaoming.next()) // {value: "小炒肉", done: false}
console.log (xiaoming.next()) // {value: "麻婆豆腐", done: false}
console.log (xiaoming.next()) // {value: "红烧鲤鱼", done: false}

使用函数表达式的方式创建一个生成器

let chef = function * (foods) {
    for(let i = 0; i < foods.length; i++) {
        yield foods[i]
    }
 }

let xiaoming = chef(['小炒肉', '麻婆豆腐', '红烧鲤鱼'])
console.log (xiaoming.next()) // {value: "小炒肉", done: false}
console.log (xiaoming.next()) // {value: "麻婆豆腐", done: false}
console.log (xiaoming.next()) // {value: "红烧鲤鱼", done: false}

继承(extend)

// 创建一个Person 类
class Person {

  // 父类中的构造函数
  constructor(name, age) {
    this.name = name
    this.age = age
  }

  // 父类中的函数
  intro() {
    return `${this.name}, ${this.age}` // xiaoming, 19
  }
}

// 再创建一个类,继承自Person类
class Chef extends Person {

  // 子类中的构造函数
  constructor(name, age) {
    // super函数可以调用父类的super
    super(name, age)
  }
}

// 创建Chef类的实例对象
let xiaoming = new Chef('xiaoming', '19')

// xiaoming.intro() 子类xiaoming调用父类的方法intro
console.log(xiaoming.intro())

申明静态方法

class Chef {
  // 将cook方法改造成静态方法
  static cook(food) {
    console.log(food) // 红烧肉
  }
}

// 使用这个静态方法,使用类的名调用即可
Chef.cook('红烧肉')

福利时间

上一篇 下一篇

猜你喜欢

热点阅读