zoukankan      html  css  js  c++  java
  • 08-TypeScript中的类

    类的概念通常是在后端开发中实现的思想,比如C#、C++或Java,传统的JavaScript开发通过使用原型模式来模拟类的功能。在TypeScript中,天生就是支持类

    的,可以让前端的开发更加具有面向对象思想开发的实现。

    class Doctor{
        public name:string;//默认不写就是public
        public getname():void {
            console.log("my name is:"+this.name);
        }
    }
    
    var doc1=new Doctor();
    doc1.name="hcc";
    doc1.getname();

    后端开发的开发者都知道类有构造函数,在JavaScript中,通过定义函数和传递参数来模拟构造函数。在上述的代码中,在实例化Doctor类时,使用了默认构造函数。

    在TypeScript中,可以显示的使用constructor关键字来定义构造函数,如下:

    class Wife{
        public name:string;
        constructor(name:string){
            this.name=name;
        }
        public getname():void{
            console.log("my wife name is:"+this.name)
        }
    }
    
    var wife=new Wife("hcc");
    wife.getname();

    另外,在后端开发语言中,属性和静态也是重要的概念,在上述代码中,需要在外部访问的我们定义为了公共字段,但不是属性的概念;另外方法的访问需要实例化类才能访问。在TypeScript中可以定义

    属性,也可以通过static关键字定义静态类型(可以不实例化也能访问的成员),如下:

    class Book{
        constructor(bookname:string){
            this._bookname=bookname;
        }
        private _bookname:string;
    
        get BookName(){
            return this._bookname;
        }
        set BookName(bookname:string){
            this._bookname=bookname;
        }
    
        public static GetBookInfo(bookname:string){
              console.log(bookname);
        }
    }
    
    var book=new Book("Advanced C#");
    console.log((book.BookName));
    Book.GetBookInfo("Advanced Static C#")

    欢迎加入QQ群讨论:573336726

  • 相关阅读:
    [LeetCode] 310. Minimum Height Trees
    [LeetCode] 722. Remove Comments
    [LeetCode] 243, 244, 245. Shortest Word Distance I, II, III
    [LeetCode] 939. Minimum Area Rectangle
    [LeetCode] 135. Candy
    [LeetCode] 1395. Count Number of Teams
    [LeetCode] 673. Number of Longest Increasing Subsequence
    [LeetCode] 724. Find Pivot Index
    [LeetCode] 1219. Path with Maximum Gold
    [LeetCode] 849. Maximize Distance to Closest Person
  • 原文地址:https://www.cnblogs.com/malaoko/p/7591539.html
Copyright © 2011-2022 走看看