物件導向

JavaScipt 原生支援物件導向,但與一搬程式落差較大。

JavaScript 物件導向

function Student(name) {
    this.name = name;
    this.getName = function () {
        return name;
    }
}

var student = new Student("Daniel");
console.log(student.getName());

類別(Class)

TypeScript 建立Class方式

class Student {
    _name: string;
    constructor(name: string) {
        this._name = name;
    }
    getName(): string{
        return this._name;
    }
}

var student: Student = new Student("James");
console.log(student.getName());

1. 屬性(Property)

  1. Class所有的資料
  2. 預設Public,私有需指定為Private
  3. 靜態屬性

2. 建構式

class 的初始化

使用方式

class Student {
    static NumOfStudent: number = 1000; //靜態屬性
    public _name: string;
    _age: number;   //Default Public
    private _birthday: Date;

    constructor(name: string, age: number, birthday: Date) {
        //設定預設值
        this._name = name;
        this._age = age;
        this._birthday = birthday;
    }
}

繼承(Inheritance)

使用extends 關鍵字繼承基底類別(Base Class)

class Animal {
    Say() {
        console.log("I'm Animal")
    }
}

class Dog extends Animal {
    Say() {
        super.Say();
        console.log("I'm Dog")
    }
}

var dog: Dog = new Dog();
dog.Say();

介面(Interface)

  1. 使用interface定義Interface
  2. 保持抽換的彈性
  3. 使用Implements 實作 interface

使用方式

interface IDiscountCalculator
{
    price: number;
    qty: number;
    Calculate(): number;
}

class OverPriceDiscountCalculator implements IDiscountCalculator {
    constructor(
        public price: number,
        public qty: number) {
    }
    Calculate() {
        var total = this.price * this.qty;
        if (total >= 500) {
            total *= 0.8;
        }
        return total;
    }
}

var calculator: IDiscountCalculator = new OverPriceDiscountCalculator(100, 2);
console.log(calculator.Calculate()); //200

模組(Module)

  1. 類似C# namespace
  2. 把程式碼分類
  3. 需使用export讓外部使用
module App.Product {
    export function isZenfone(name) {
        if(name.indexOf("Zenfone")>-1)
            return true;
        return false;
    }
}

console.log(App.Product.isZenfone("Zenfone3"));

results matching ""

    No results matching ""