TypeScript learning(2)

81 阅读1分钟

autofix

//保存的时候自动修复一些eslint的错误

{
    "tslint.autoFixOnSave": true
}

疑问: 直接把前面的也改掉了

class CustomArray extends Array {
    constructor(...args) {
        super(...args)
    }
}
const arr = new CustomArray(3,3,4)
console.log(arr)
//数组全部填充
arr.fill('+')
console.log(arr)
arr.fill('-')
console.log(arr)
//数组拼接成字符串
arr.join('_')

original_9b24b1b113d059e535ea15a4bf3a84c1.png

继承

// es5:构造函数先创建子构造函数的实例this,然后将父构造函数的属性方法添加到这个this上

// es6:先从父类取到实例对象this,在调用super函数后,再将子类的属性方法添加到这个this上

// 继承 
// es5中继承要修改原型链
// 函数的继承
function Food() {
    this.type = 'food'
}
Food.prototype.getType = function(){
    return this.type
}
function Vegetables(name) {
    this.name = name
}
// 让Vegetables继承Food的构造函数 
Vegetables.prototype = new Food()
const tamato = new Vegetables('tamato')
console.log(tamato.getType())

// es6中类的继承
class Parent {
    constructor(name) {
        this.name = name
    }
    getName() {
        return this.name
    }
    static getName(){
        return this.name
    }
}
class Child extends Parent {
    constructor(name, age) {
        // 只有调用了super方法之后 才能在子类中用this
        super(name)
        this.age = age
    }
}
const c = new Child('mitty', 18)
console.log(c)
console.log(c.getName())
console.log(c instanceof Child) //true
console.log(c instanceof Parent)//true
console.log(Child.getName()) //Child
//获取构造函数的原型对象
console.log(Object.getPrototypeOf(Child) === Parent)

ts中的继承

class Parent {
    name: string
    constructor (name: string) {
        this.name = name
    }
}
class Child extends Parent {
    constructor(name: string) {
        super(name)
    }
}