ES5 沒有 class 那替代方法是?


Posted by YongChenSu on 2020-12-09

每次創建新 function 耗費記憶體

function Dog(name) {
  var myName = name
  return {
    getName: function() {
      return myName
    },
    sayHello: function() {
      console.log(myName)
    }
  }
}

var d = Dog('abc')
var b = Dog('123')

console.log( d.sayHello === b.sayHello) // false


ES5 還是可以 new

function Dog(name) {
  this.name = name
}

var d = new Dog('abc')
console.log(d) // Dog {name: 'abc'}


prototype

function Dog(name) {
  this.name = name
}

Dog.prototype.getName = function() {
  return this.name
}

Dog.prototype.sayHello = function() {
  console.log(this.name)
}

var d = new Dog('abc')
d.sayHello() // abc
var b = new Dog('777')
console.log(b.getName()) // 777
console.log(d.sayHello === b.sayHello) // true


class 跟 ES5 的 prototype 比較



d.proto === Dog.prototype

new 設定好 proto === prototype

function Dog(name) {
  this.name = name
}

Dog.prototype.getName = function() {
  return this.name
}

Dog.prototype.sayHello = function() {
  console.log(this.name)
}

var d = new Dog('abc')
d.sayHello() // abc
console.log(d.__proto__ === Dog.prototype) // true
console.log(d.__proto__.__proto__ === Object.prototype) // ture
console.log(d.__proto__.__proto__.__proto__ === null) // true
console.log(Dog.__proto__ === Function.prototype) // true


prototype chain 原型練

d.sayHello()

1. d 身上有沒有 sayHello
2. d.__proto__ 有沒有 sayHello
3. d.__proto__.__proto__ 有沒有 sayHello
4. d.__proto__.__proto__.__proto__ 有沒有 sayHello
5. null 找到頂


a.toString === String.prototype.toString

var a = '123'
console.log(a.__proto__ === String.prototype) // true
console.log(a.toString === String.prototype.toString) //true


在 prototype 上加上自訂 function

String.prototype.first = function() {
  return this[0]
}
var a = '123'
console.log(a.first())


原型鍊跟 instance 本身要有東西連接起來

透過 proto 這個屬性連接來

參考資源


#程式導師實驗計畫第四期 #前端 #class #ES5







Related Posts

Day 20 & 21-Snake Game

Day 20 & 21-Snake Game

不可不知的小工具-C#字串長度處理

不可不知的小工具-C#字串長度處理

Git change specific commit message

Git change specific commit message


Comments