# Day16 【牙起來】 成員、方法 - Typescript
將我們前幾天的小遊戲程式 `store.component.ts` 拿出來

整個 `.ts` 檔案都是用 `Typescript` 語法
我們將其中的 `class` 物件部分拿出來,貼到Typescript專案的 `main.ts` 上分析
並且要拿掉程式碼 `implements OnInit`
因為這段是給Angular專案看的
> 或者說因為沒有 `@angular/core` 的 `node_modules`包
> 沒得使用,所以才要拿掉
>
> 
## Angular中的物件
接下來我們來看一下何謂Angular元件中的**物件**
以下是 `main.ts` 檔案
```typescript=
export class StoreComponent {
weapons = [
{name: '小劍', atk: '5'},
{name: '彎刀', atk: '7'},
{name: '大魔劍', atk: '11'}
];
constructor() {
}
ngOnInit(): void {
}
}
```

接下來執行
> tsc main.ts
來看一下生成出來的 `.js` 檔案

```javascript=
"use strict";
exports.__esModule = true;
exports.StoreComponent = void 0;
var StoreComponent = /** @class */ (function () {
function StoreComponent() {
this.weapons = [
{ name: '小劍', atk: '5' },
{ name: '彎刀', atk: '7' },
{ name: '大魔劍', atk: '11' }
];
}
StoreComponent.prototype.ngOnInit = function () {
};
return StoreComponent;
}());
exports.StoreComponent = StoreComponent;
```
可以看見用**Javascript**語法編寫而成的一個物件
等於說你寫短短少少的幾行`.ts`文字,等同於以上落落長的`.js`程式碼
## 成員 與 方法
仔細看程式碼的其中一部份
`StoreComponent` 是一個物件變數,底下有
* `StoreComponent()` 方法,其中裡面有 `weapons` 成員
* `ngOnInit` 方法

這也就是為什麼在前面章節提到
**不是變數(Variable)** 而是**成員(Member)**
**不是函式(Function)** 而是**方法(Method)**
因為這些東西、功能被包裝成了一個物件,是物件底下的功能
在物件導向的世界裡
原本認知的變數就稱作**成員(Member)**
原本認知的函式就稱作**方法(Method)**
在前幾天的小遊戲中
我們在程式碼使用`this` ,代表了**這個物件本身**
是透過 `this.hp` 來取得這個物件底下的成員 `hp`

## 複雜一點的程式碼
我們拿掉 `ngOnInit()` 與 `constructor()`
然後新增一些東西,在`.ts`的**方法**裡面寫**函式**
```typescript=
export class StoreComponent {
atk = 1;
weapons = [
{name: '小劍', atk: '5'},
{name: '彎刀', atk: '7'},
{name: '大魔劍', atk: '11'}
];
addAtk() {
this.atk += 1;
}
test() {
let a = '10';
let printHello = function () {
console.log('Hello');
}
printHello()
}
}
```
編譯完後的`.js`
```javascript=
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.StoreComponent = void 0;
class StoreComponent {
constructor() {
this.atk = 1;
this.weapons = [
{ name: '小劍', atk: '5' },
{ name: '彎刀', atk: '7' },
{ name: '大魔劍', atk: '11' }
];
}
addAtk() {
this.atk += 1;
}
test() {
let a = '10';
let printHello = function () {
console.log('Hello');
};
printHello();
}
}
exports.StoreComponent = StoreComponent;
```
* 橘色區塊代表**物件(Object)**
* 綠色區塊是**方法(Method)**
* 黃色區塊是**成員(Member)**
* 藍色區塊是**變數(Variable)、函式(Function)**

我們在 `.ts` 檔中沒有寫 `constructor()`
可是編譯完後出現在 `.js` 檔案中
代表 `constructor` 是物件構件時的必要步驟
> 若能看懂以上的物件結構對應關係,恭喜你已經完成32%的Typescript