JavaScript的物件基於「原型」的繼承,可以令一個物件「繼承另一個物件的屬性」。具體上,以 Object.setPrototypeOf() 指定原型關係。詳:
『Object.setPrototypeOf() - JavaScript | MDN』
所有的物件都有proto屬性
// 對 prototype 物件新增 attack 屬性,值是後面的 function
Hero.prototype.attack = function() {
console.log("attack")
//
}
const a = { } // 空物件寫法
const b = Object.create(null) // 指定原形,建立新物件
函式(function)如同 { } 可以用來建構物件,把他當成一般物件來用可以做到以下的事。
function heroCreater(name, action) {
const attack = () => {
console.log(`${name}使用絕招${action}`)
}
return {
name,
action,
attack
// 當參數和屬性同名時,可省略值不寫
// 原本應該長成 name: name,
}
}
const h = heroCreater("小傑", "剪刀石頭石頭")
h.attack()
// "小傑使用絕招剪刀石頭石頭"
console.log(h)
// [object Object] {
// action: "剪刀石頭石頭",
// attack: () => {
// window.runnerWindow.proxyConsole.log(`${name}使用絕招${action}`)
// },
// name: "小傑"
// }
console.log(h.action)
// "剪刀石頭石頭"
function Hero(name, action) {
this.name = name
this.action = action
}
若const對function加new
function hello() {
console.log("hi")
}
const h = new hello()
console.log(h)
// hello { } ,裡面的 this = 函式名稱 + 空物件
console.log(this)
// { } ,外面的 this 空物件
---------------------------
const h = hello()
console.log(h)
// undefined,沒有 return 值
所有的 function 都有回傳值,當沒有寫 return 時會有兩種預設值:
JavaScript沒有class,這是ES6才有的語法糖衣,本質上還是使用__proto__去做事。結構可以看成:
class => new => instance(實體)
(烤盤) (透過) (雞蛋糕)
如果 new Hero() 想帶引數進去,一定要搭配建構子constructor()使用。
constructor 裡面只放屬性,行為請寫在外面。
class Hero {
constructor(name) {
this.name = name
}
}
let h = new Hero("奇犽")
console.log(h)