15、TypeScript 之构造器 constructor 方法 methods

沙摩柯
• 阅读 10023

如果你期望拥有若干个参数再创造一些实例对象 那如何写呢

class Movie {
  name: string;
  play_count: number;
  create_at: string;
  constructor(name: string, play_count: number = 12, create_at: string) {
    // this 指向生成点 Object 本身
    this.name = name;
    this.play_count = play_count;
    this.create_at = create_at;
  }
 
  // methods 可以对 data 进行操作
  display_play_count(padding: string = '***') {
    return this.play_count + '次' + padding    
  }
  increase_play_count() {
    this.play_count += 1;
  }
}

let a = new Movie('阿丽塔:战斗天使', undefined, '17点28分');

a.increase_play_count();  // 13***  虽然第二个参数并没有传递 可以使用 undefined 来占位 会使用默认值 12 再 += 1

console.log(a, a.display_play_count());  // Movie { name: '阿丽塔:战斗天使', play_count: 13, create_at: '17点28分' } '13次***'

希望看了以上代码 可以对你对学习 TS 有所帮助。

点赞
收藏
评论区
推荐文章
blmius blmius
4年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Oracle 分组与拼接字符串同时使用
SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(
待兔 待兔
1年前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Jacquelyn38 Jacquelyn38
4年前
你不可不知的JS面试题(第二期)
1、什么是继承?子类可以使用父类的所有功能,并且对功能进行扩展。新增方法改用方法(1)、ES6使用extends子类继承父类的方法。// 父类    class A        constructor(name)            this.name name;                getNa
Stella981 Stella981
4年前
Hive 删除行, 表 ,清空表
删除行A表数据如下id(String)       name(String)\1                       aaa2                      bbb3                      ccc\
Stella981 Stella981
4年前
Egret 类的创建和继承
classtestextendsegret.DisplayObjectContainer{/类的创建///属性name:string;age:number;ts:test;//可传参的构造方法publicconst
Easter79 Easter79
4年前
String.intern()引发的性能问题
项目代码中用到反射,伴随大量的NoSuchFieldException异常,发现cpu飙高,排查后发现跟String.intern有关。在Class中有连个常见的方法:Ø public Field getField(String name)Ø getMethod(String name, Class<?... parameterTypes)
Stella981 Stella981
4年前
HIVE 时间操作函数
日期函数UNIX时间戳转日期函数: from\_unixtime语法:   from\_unixtime(bigint unixtime\, string format\)返回值: string说明: 转化UNIX时间戳(从19700101 00:00:00 UTC到指定时间的秒数)到当前时区的时间格式举例:hive   selec
Stella981 Stella981
4年前
C# 中合并2个 Dictionary
内置方法usingSystem.Collections.Generic;usingSystem.Linq;Dictionary<string,objectdicAnewDictionary<string,object(){{"Name","姓名"},
Wesley13 Wesley13
4年前
Unity横屏
Android下发现Unity里面的Player设置,并不能完全有效,比如打开了自动旋转,启动的时候还是会横屏,修改XML添加以下代码<applicationandroid:icon"@drawable/ic\_launcher"                    android:label"@string/app\_name"
Stella981 Stella981
4年前
ES6入门六:class的基本语法、继承、私有与静态属性、修饰器
基本语法继承私有属性与方法、静态属性与方法修饰器(Decorator) 一、基本语法1classGrammar{2constructor(name,age){//定义对象自身的方法和属性3this.namename,