angular的封装与继承

面向对象的三大特征是继承、封装、多态。JavaScript可以模拟实现继承和封装,但是无法很好的模拟实现多态,所以我们说JavaScript是一门基于对象的语言,而非是面向对象的语言。 当然在TypeScript可以实现多态,后面会有实例讲到。

参考网址:https://github.com/Murphycx94/blog/issues/30

step1: D:\vue\untitled2906\src\app\SomeClass.ts

export namespace App {
  export class SomeClass {
    public name;
    public age;
    public address;

    constructor(name: string, age: number, address: string) {
      this.name = name;
      this.age = age;
      this.address = address;
    }

    getName() {
      return this.name;
    }

    setName(name: string) {
      this.name = name;
    }

    getAge() {
      return this.age;
    }

    setAge(age: number) {
      this.age = age;
    }

    getAddress() {
      return this.address;
    }

    setAddress(address: string) {
      this.address = address;
    }

    toString() {
      return "Name{" +
        "name='" + this.name + '\'' +
        ", age=" + this.age +
        ", address='" + this.address + '\'' +
        '}';
    }
  }
}

step2: D:\vue\untitled2906\src\app\SomeData.ts

import {App} from './SomeClass';

export namespace App2 {
  import SomeClass = App.SomeClass;

  export class SomeData extends SomeClass{
    getData(){
      return this.address;
    }
  }
}

step3: D:\vue\untitled2906\src\app\app.component.ts

import {Component} from '@angular/core';
import {App2} from './SomeData';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'untitled2906';
  select = 0;//页面对应抽奖下标
  timer: any;

  ngOnInit() {
    let mSomeClass = new App2.SomeData("张飞",18,'河北石家庄');
    mSomeClass.setName('赵云');
    mSomeClass.setAge(22)
    mSomeClass.setAddress('河南濮阳');
    let name = mSomeClass.toString();
    let ages = mSomeClass.getAge();

    let hello = mSomeClass.getData();
    console.log(name);
    console.log(ages);
    console.log(hello);
  }
}

run:

Name{name='赵云', age=22, address='河南濮阳'}
app.component.ts:25 22
app.component.ts:26 河南濮阳

end