bind, call, apply

在未经过绑定的this会指向Windows

Bind

使用Bind会return 一个function


let Dennis = {
    name: "Dennis",
    age: 22
}
function hello() {
    console.log(this) //指向Window
    console.log(this.age)
}

hello() //undefined

https://ithelp.ithome.com.tw/upload/images/20210521/20130419Qo7Dszql1s.png


所以这边使用bind method绑定在指定的物件身上


let Dennis = {
    name: "Dennis",
    age: 22
}
function hello() {
    console.log(this) //指向Dennis
    console.log(this.age) //22
}

const Hello = hello.bind(Dennis)
Hello()

https://ithelp.ithome.com.tw/upload/images/20210521/20130419pJPOs52ZVh.png


Call

使用call 会直接执行,所以不需要变数接住function再执行

let Dennis = {
    name: "Dennis",
    age: 22
}
function hello() {
    console.log(this) //指向Dennis
    console.log(this.age) //22
}

hello.call(Dennis)

并且 call可以传入参数

let Dennis = {
    name: "Dennis",
    age: 22
}
function hello(parameter) {
    console.log(`My name is ${this.name} phonenumber is ${parameter}`)
}

hello.call(Dennis,) //My name is Dennis phonenumber is undefined

加入参数

let Dennis = {
    name: "Dennis",
    age: 22
}
function hello(parameter) {
    console.log(`My name is ${this.name} phonenumber is ${parameter}`)
}

hello.call(Dennis, "0900123123") //My name is Dennis phonenumber is 0900123123

Apply

apply跟call几乎一样,不同於传入参数型态,若是array使用apply,string等等使用call


let c = ["000000"]

let Dennis = {
    name: "Dennis",
    age: 22
}
function hello(parameter) {
    console.log(`My name is ${this.name} phonenumber is ${parameter}`)
}

hello.apply(Dennis, c) //My name is Dennis phonenumber is 000000

<<:  Class

>>:  Git l

【Day26】反馈元件 - Progress bar

元件介绍 Progress bar 是能够展示当前进度的进度条元件。当一个操作需要显示目前百分比,或...

[3D地图-CesiumJS系列] 三、车辆废气排放地图 - 以粒子系统(Particle system)实作

本篇文章请搭配 [3D地图-CesiumJS系列] 一、快速上手 [3D地图-CesiumJS系列]...

【从实作学习ASP.NET Core】Day14 | 後台 | 用 Identity 实作会员功能

今天要用 .NET Core 自带的使用者管理套件 Identity 来实现网站的会员功能 ASP....

[Day 26] Web 小厨娘

今天晚餐是我掌厨 妈妈跟我一起备料当二厨 煮了4菜一汤切水果 虽然我觉得煎鱼比较难 但煮饭还是一件很...

快乐很简单,但要简单却很难。

快乐很简单,但要简单却很难。 It is very simple to be happy, but ...