我想从另一个班级访问一个数组 的 FirstClass.ts
items:any = [];
export class ContainsDataArray {
saveItems(item){
this.items.push(item);
}
}
二等
export class AccessArrayfromAnotherClass {
(Call the array from the FirstClass this.items to be exact)
}
答案 0 :(得分:0)
这个怎么样:
class A {
static array: number[] = [1, 2, 3];
constructor() {}
}
class B {
constructor() {}
getArray() {
console.log(A.array);
}
}
f = new B();
f.getArray();
答案 1 :(得分:0)
在面向对象编程(OOP)中,您可以使用合成或继承。
class ContainsDataArray {
constructor() {
this._items = [];
}
saveItem(item) {
this._items.push(item);
}
get items() {
return this._items;
}
}
class AccessArrayfromAnotherClass {
constructor() {
this._ref = new ContainsDataArray();
}
get ref() {
return this._ref;
}
}
let instance = new AccessArrayfromAnotherClass();
instance.ref.saveItem('Foo');
instance.ref.saveItem('Bar');
console.log(instance.ref.items);

class ContainsDataArray {
constructor() {
this._items = [];
}
saveItem(item) {
this._items.push(item);
}
get items() {
return this._items;
}
}
class AccessArrayfromAnotherClass extends ContainsDataArray {}
let instance = new AccessArrayfromAnotherClass();
instance.saveItem('Foo');
instance.saveItem('Bar');
console.log(instance.items);