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)
>>: Day28:【技术篇】ASP DOT NET CORE 的 MVC 基础入门
小弟因疫情影响,整天在家苦等Offer 於是心血来潮,将自己之前的考题整理成笔记 上来与大家分享交流...
引言 今天是我第二次参赛的赛末点, 我认为自己写的内容都不深,参加铁人赛算是自己入门 CTF 的纪...
一直以来,我们使用 TeamCity 时都是透过 Web UI 来设定,不论 Project 的 V...
Many of our business campaign advisors are analyti...
阿嬷都看得懂的通用 .html 档案结构 不知道各位聪明的阿嬷是否注意到,在前几天的讨论中,我们其实...