简体   繁体   English

如何通过es6类构造数组

[英]How to Construct an array by es6 class

I expect that a class return an array when I new it 我期望一个类在我new时返回一个数组

class MyArray {
  constructor(){

  }
}

const myArray = new MyArray()
Array.isArray(myArray) // Should be true

I used to write it in this way: 我以前是这样写的:

class MyArray {
  constructor(){
    const arry = new Array()
    return arry
  }
}

But when I write in Typescript,the return value arry is not the type of MyArray, so it prompt an error. 但是,当我在写打字稿,返回值arry不是MYARRAY的类型,所以它提示错误。

How to fixed this problem? 如何解决这个问题?

Just extend Array and return true in the constructor 只需扩展Array并在构造函数中 return true

class MyArray extends Array{
  constructor(){
    super()
  }
}

Demo 演示版

 class MyArray extends Array{ constructor(){ super() } } myArray2 = new MyArray() console.log(Array.isArray(myArray2)); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM