Day-21 物件与原型链

JavaScript的物件基於「原型」的继承,可以令一个物件「继承另一个物件的属性」。具体上,以 Object.setPrototypeOf() 指定原型关系。详:
『Object.setPrototypeOf() - JavaScript | MDN』

建立空物件

所有的物件都有proto属性

  • 预设是 prototype = { }。
  • 使用後可以找到他的原型。___proto___找东西,会往Array.prototype找。
  • .map 方法其实是 prototype 里面的属性,後面的值是 function,用来做事。
//  对 prototype 物件新增 attack 属性,值是後面的 function
Hero.prototype.attack = function() {
    console.log("attack")
//  
}

写法1

  • 先宣告一个空阵列,填入属性
  • 若key与value同名,可从 名字:名字 {name:name}改为 名字,
const a = { } // 空物件写法

写法2

const b = Object.create(null)  // 指定原形,建立新物件

延伸:建构函式

函式(function)如同 { } 可以用来建构物件,把他当成一般物件来用可以做到以下的事。

  • 物件都有___proto___属性。
  • 所有function都有prototype属性,预设的 { } 是空阵列。
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)
//  "剪刀石头石头"

原型链 prototype chain

  • 连续使用__proto__可以一层一层往上找到原型。
  • 正常之下,印出没有的属性应该要会得到 Error,但在 JS 会得到 undefined,若再呼叫会得到 TypeError。
  • 建构函式,通常会把函式名称的首字改成大写 hero => Hero ,方便辨识这是「物件」。
function Hero(name, action) {
  this.name = name
  this.action = action
}

若const对function加new

  1. 建立一个空物件
  2. 把 this指向空物件 { }
  3. 把 this.proto 指向 Hero.prototype (预设值: { } )
  4. 自动 return this (自己多加return没用,除非是物件或阵列)
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 时会有两种预设值:

  • 一般的 function 会回传 undefined
  • 使用 new 建立的 function 会回传 this 的值
    • Class 就像蓝图
    • Instance就像new出来的实体

建构子 constructor

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)

<<:  Day 27 记忆体的管理

>>:  Day28:【技术篇】ASP DOT NET CORE 的 MVC 基础入门

复习基础JavaScript

小弟因疫情影响,整天在家苦等Offer 於是心血来潮,将自己之前的考题整理成笔记 上来与大家分享交流...

[2021铁人赛 Day30] 尾声 / Web Exploitation Web渗透题目 03

引言 今天是我第二次参赛的赛末点, 我认为自己写的内容都不深,参加铁人赛算是自己入门 CTF 的纪...

第三十天:为 TeamCity 设计的 Kotlin DSL

一直以来,我们使用 TeamCity 时都是透过 Web UI 来设定,不论 Project 的 V...

Best Digital Marketing Comapny | Siapteh

Many of our business campaign advisors are analyti...

[Day 16] 阿嬷都看得懂的通用 .html 档案结构

阿嬷都看得懂的通用 .html 档案结构 不知道各位聪明的阿嬷是否注意到,在前几天的讨论中,我们其实...