Skip to content

Instantly share code, notes, and snippets.

@idhowardgj94
Last active February 14, 2020 02:02
Show Gist options
  • Save idhowardgj94/344ce476f2f9fedf5b9225c6bc4776a7 to your computer and use it in GitHub Desktop.
Save idhowardgj94/344ce476f2f9fedf5b9225c6bc4776a7 to your computer and use it in GitHub Desktop.
javascript
const a = Object.create({
 localVar: 1
 count: () => {
  this.localVar = this.localVar + 1
  console.log("localVar now is " + this.localVar)
 }
})

// 以上等價於
function object() {
  // 建構子
  this.localVal = 1
  this.count = () => {
    this.localVal = this.localVal + 1
    console.log("localVar now is " + this.localVar)
  }
}
const a = new object()

/**
* 2/13更新: 其實以上並不完全等價,object.create是產生一個物件,並且繼承參數1中的物件原型(不過一般來說,原型不太會有狀態(變數)
* 因為原型是所有繼承的物件共用)。
* 而使用function 並 new出來,是產生一個object,其中包含constructor中的方法和參數。
* object.create應該是等價於 object.prototype = // Object.create(<object>)的<object>
*
* 另外,上一版的程式不能run,因為Object是js中物件的建構子,override就爆了。我原本實驗完
* 以為該這樣概念比較好懂。。。
**/
// 直接宣告物件會有問題,因為this指向全域物件(window)
const a = {
  // 無法access
 localVar: 1
 count: () => {
  // 會找不到this.localVal,因為在window中沒被定義過
  this.localVar = this.localVar + 1
  console.log("localVar now is " + this.localVar)
 }
}
@idhowardgj94
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment