0

## TypeScript 學習筆記

717 2019-06-22 14:45:46949 瀏覽

### class

ts是物件導向語言，因此要好好利用它，就是要將相關聯的變數、方法都群組在一起，也就是使用class。

``````class Point{
x:number, //稱為field
y:number,

draw(){ //稱為method
console.log('x:',this.x,' y:',this.y);
}
getDistance(){
//...
}
}
``````

``````let point1 = new Point; // point1就是依據class Point建立的instance
point1.draw(); //x:undefine,y:undefine (´⊙ω⊙`)
``````

### Constructor

``````class Point{
x:number, //稱為field
y:number,

constructor(x:number, y:number){
this.x = x;
this.y = y;
}

draw(){ //稱為method
console.log('x:',this.x,' y:',this.y);
}
}
``````

``````let point2 = new Point(8,24);
point2.draw(); //x:8,y:24 ヽ(✿ﾟ▽ﾟ)ノ
``````

``````class Point{
x:number, //稱為field
y:number,

constructor(x?:number, y?:number){
this.x = x;
this.y = y;
}

draw(){ //稱為method
console.log('x:',this.x,' y:',this.y);
}
getDistance(){
//...
}
}

let point2 = new Point();
``````

### access modifier

``````let point2 = new Point(8,24);

point2.x=4;
point2.y=12;

point2.draw(); //x:4,y:12 Σ(;ﾟдﾟ)
``````

``````class Point{
private x:number, //用private把x & y藏得好好的
private y:number,

constructor(x:number, y:number){
this.x = x;
this.y = y;
}

draw(){ //稱為method
console.log('x:',this.x,' y:',this.y);
}
}

let point2 = new Point(8,24);

point2.x=4; //錯誤訊息
point2.y=12; //錯誤訊息

point2.draw(); //x:8,y:24 ヽ(✿ﾟ▽ﾟ)ノ
``````

``````class Point{
constructor(public x:number,private y:number){
}

draw (){ //method
console.log('x:',this.x,' y:',this.y);
}
}
``````

``````class Point{
constructor(public x:number,private y:number){
}

draw (){ //method
console.log('x:',this.x,' y:',this.y);
}

getX(){ //呼叫這個方法就能知道x值是甚麼
return this.x;
}
setX(value){ //呼叫此方法，設定value只要是大於0，就能改變x值更新成value。
if(value <= 0){
throw new Error('X不能小於0');
}else
this.x = value;
}
}
``````

TS當然也知道大家有這種需求，所以其實get與set是個將X設為Point的property的語法。

``````    get X(){ //稱作getter
return this.x;
}
set X(value){ //稱作setter
if(value <= 0){
throw new Error('X不能小於0');
}else
this.x = value;
}
``````

``````class Point{
constructor(private _x:number,private _y:number){
}

draw (){ //method
console.log('x:',this._x,' y:',this._y);
}

get x(){
return this._x;
}
set x(value){
if(value <= 0){
throw new Error('X不能小於0');
}else
this._x = value;
}
}

let point = new Point(1,2);
point.x; //使用getter
point.x = 10; //使用setter
``````

## Module

``````//point.ts檔

export class Point{
constructor(private _x:number,private _y:number){
}

draw (){ //method
console.log('x:',this._x,' y:',this._y);
}

get x(){
return this._x;
}
set x(value){
if(value <= 0){
throw new Error('X不能小於0');
}else
this._x = value;
}
}
``````
``````//欲使用Point的ts檔

import { Point } from './point'; //from相對路徑，後面沒有.ts喔

let point = new Point(1,2);
point.x; //使用getter
point.x = 10; //使用setter
``````