---
# System prepended metadata

title: this
tags: [JavaScript]

---

###### tags: `JavaScript`

# this

## 默認綁定
``` javascript=
function girl(){
    console.log(this)
}
girl()
```
:::spoiler 
Windows
:::
## 隱式綁定
```javascript=
var girlName = {
    name:"小紅",
    callName(){
        console.log(this.name)
    }
}
girlName.callName()
```
:::spoiler
小紅
:::
## 硬綁定
```javascript=
var girlName = {
    name: "小紅",
    callName() {
        console.log(this.name)
    }
}
var girl1 = {
    name: "小白"
}
girlName.callName.call(girl1)//小白
```
## 建構式綁定
```javascript=
function Lover(name){
    this.name = name
    this.callName=function(){
        console.log(this.name)
    }
}
var name = "小白"
var allen = new Lover('小紅')
allen.callName()
```
:::spoiler 
小紅
:::
## 測試
```javascript=
function a() {
  function b() {
    console.log(this);
    function c() {
      "use strict";
      console.log(this);
    }
    c();
  }
  b();
}
a();
```
:::spoiler
Window
undefined
:::

```javascript=
var name = "小白";

function special() {
  console.log(this.name);
}

var girl = {
  name: "小紅",
  callName() {
    console.log(this.name);
  },
  woman: {
    name: "小黃",
    callName() {
      console.log(this.name);
    },
  },
  special,
};
girl.callName();
girl.woman.callName();
girl.special();
```
:::spoiler
小紅
小黃
小紅
:::

```javascript=
var name = "小紅";
function a() {
  var name = "小白";
  console.log(this.name);
}
function d(i) {
  return i();
}
var b = {
  name: "小黃",
  detail() {
    console.log(this.name);
  },
  closure() {
    return function () {
      console.log(this.name);
    };
  },
};
var c = b.detail;
b.a = a;
var e = b.closure();
a();
c(); 
b.a(); 
d(b.detail); 
e(); 
```
:::spoiler
小紅
小紅
小黃
小紅
小紅
:::
## 箭頭函式
```javascript=
var auntie = {
  name: '阿姨',
  callSomeone() {
    console.log(this.name)
    setTimeout(() => {
      console.log(this.name)
    }, 100);
  }
}
auntie.callSomeone();
```