为什么一个const必须在打字稿的导出类之外?
问题描述:
这是一个与打字稿范围有关的问题。该listofstuff不变作品,如果它的类右括号外的,但如果它是括号内为什么一个const必须在打字稿的导出类之外?
例如,这个代码不工作:
import {Injectable} from '@angular/core'
@Injectable()
export class EventListService{
getEvents(){
return listofstuff
}
const listofstuff = [
{name:'Angular Connect', date: '9/26/2036', time: '10am', location: {address: '1 London Rd', city: 'London', country: 'England'}},
{name:'ng-nl', date: '4/15/2037', time: '9am', location: {address: '127 DT ', city: 'Amsterdam', country: 'NL'}},
{name:'ng-conf 2037', date: '4/15/2037', time: '9am', location: {address: 'The Palatial America Hotel', city: 'Salt Lake City', country: 'USA'}},
{name:'UN Angular Summit', date: '6/10/2037', time: '8am', location: {address: 'The UN Angular Center', city: 'New York', country: 'USA'}},
]
}
但这个工程:
import {Injectable} from '@angular/core'
@Injectable()
export class EventListService{
getEvents(){
return listofstuff
}
}
const listofstuff = [
{name:'Angular Connect', date: '9/26/2036', time: '10am', location: {address: '1 London Rd', city: 'London', country: 'England'}},
{name:'ng-nl', date: '4/15/2037', time: '9am', location: {address: '127 DT ', city: 'Amsterdam', country: 'NL'}},
{name:'ng-conf 2037', date: '4/15/2037', time: '9am', location: {address: 'The Palatial America Hotel', city: 'Salt Lake City', country: 'USA'}},
{name:'UN Angular Summit', date: '6/10/2037', time: '8am', location: {address: 'The UN Angular Center', city: 'New York', country: 'USA'}},
]
来自面向对象的背景(C#和一些Java),这对我来说很奇怪。有人可以解释这里发生了什么吗?即使在第一个示例中使用“this”关键字也不起作用...
答
对于类属性,不能使用const
关键字。相反,类属性只能标记为public
,private
,readonly
和protected
修饰符。
import { Injectable } from '@angular/core'
@Injectable()
export class EventListService {
readonly listofstuff: any[] = [
{ name: 'Angular Connect', date: '9/26/2036', time: '10am', location: { address: '1 London Rd', city: 'London', country: 'England' } },
{ name: 'ng-nl', date: '4/15/2037', time: '9am', location: { address: '127 DT ', city: 'Amsterdam', country: 'NL' } },
{ name: 'ng-conf 2037', date: '4/15/2037', time: '9am', location: { address: 'The Palatial America Hotel', city: 'Salt Lake City', country: 'USA' } },
{ name: 'UN Angular Summit', date: '6/10/2037', time: '8am', location: { address: 'The UN Angular Center', city: 'New York', country: 'USA' } },
];
getEvents() {
return this.listofstuff;
}
}
你会使用this
关键字访问listofstuff
类属性。 Example
您可以在官方documentation中了解更多关于Typescript类的信息。请记住,默认情况下属性和没有标识符的成员标记为public
。从文档:
在TypeScript中,每个成员默认情况下都是公共的。
希望有帮助!
+0
非常有帮助。谢谢! –
你不能有'const'对象属性(你能吗?) – Pointy
在TypeScript中,[在类范围内](https://github.com/Microsoft/TypeScript/issues/12),必须使用'只读“而不是”const“。另见https://stackoverflow.com/questions/46561155/difference-between-const-and-readonly-in-typescript – artem