ES6-Class類1/2

筆記。

 1.ES5和ES6實現創建實例

// ES5中創建實例
function Point(x, y) {
  this.x = x;
  this.y = y;
}
Point.prototype.getPosition = function() {
  return '(' + this.x + ', ' + this.y + ')'
}
var p1 = new Point(2, 3)
console.log(p1) // Point {x: 2, y: 3}
console.log(p1.getPosition()) // (2, 3)

// ES6中class創建實例
class Point2 {
  constructor(x,y) {
    this.x = x;
    this.y = y;
  }
  getPosition() {
    return `(${this.x}, ${this.y})`
  }
}
const p2 = new Point2(5, 6)
console.log(p2)
console.log(p2.getPosition())
console.log(p2.hasOwnProperty('x')) // true
console.log(p2.hasOwnProperty('getPosition2')) // false
console.log(p2.__proto__.hasOwnProperty('getPosition2')) // true

2.ES5和ES6存取值函數

// ES5
var info = {
  _age: 18,
  set age(newValue) { // 同名的set和get
    if(newValue > 18) {
      console.log('why old')
    } else {
      console.log('so young')
    }
  },
  get age() {
    console.log('age is a secret')
    return this._age
  }
}
console.log(info.age) // age is a secret 18
info.age = 13 // so young
// ES6
class Info {
  constructor(age) {
    this._age = age
  }
  set age(newAge) {
    console.log('set age')
    this._age = newAge
  }
  get age() {
    console.log('get age')
    return this._age
  }
}
const info2 = new Info(18)
info2.age = 12 // set age
console.log(info2.age) // get age 12

3.class兩種定義方式

// 函數的兩種定義形式
const func = function() {}
function func2() {}
// class的兩種定義形式
class Info3 {
  constructor() {}
}
const Info4 = class c { // 實際類名是 = 前面的Info4 (c可以不寫)
  constructor() {}
}

4.static 靜態方法

// 定義在類裏面的方法會被實例繼承,如果不希望實例繼承,用static
class Point3 {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
  getPosition() {
    return `(${this.x}, ${this.y})`
  }
  static getClassName() {
    return Point3.name
  }
}
const p = new Point3(8, 9)
console.log(p.getPosition())
// console.log(p.getClassName()) // 報錯
// 靜態屬性
class Point4 {
  constructor() {
    this.x = 0;
  }
}
Point4.y = 2
const p4 = new Point4()
console.log(p4.x) // 0
console.log(p4.y) // undefined

下午睡着了,太困了,想好好睡覺,熬不下去了。

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