mxl*_*xle 1 angularjs typescript angular
在 javascript 中我会这样做:
function a(b,c) {this.foo = b; this.bar = c; this.yep = b+c}
// undefined
b = new a(1,2)
// a {foo: 1, bar: 2, yep: 3}
Run Code Online (Sandbox Code Playgroud)
但我还没有找到任何方法在打字稿中做到这一点。这些都不起作用:
class A {
foo: number;
bar: number;
yep: foo + bar;
}
class A {
foo: number;
bar: number;
yep: this.foo + this.bar;
}
class A {
foo: number;
bar: number;
let yep:number = this.foo + this.bar;
}
class A {
foo: number;
bar: number;
yep: number;
constructor() {
this.yep = this.foo + this.bar;
}
}
class A {
foo: number;
bar: number;
get yep(): number {
return this.foo + this.bar;
}
}
class A {
foo: number;
bar: number;
yep: function () {return this.get("foo") + this.get("bar")};
}
Run Code Online (Sandbox Code Playgroud)
我这样初始化它:
somevar: A = {
foo: 1,
bar: 2
}
Run Code Online (Sandbox Code Playgroud)
我也尝试过这个:
somevar: A = {
foo: 1,
bar: 2,
this.yep: this.foo + this.bar
}
Run Code Online (Sandbox Code Playgroud)
感谢您的帮助。这个数学将会更加困难,而且我会不止一次需要它,所以我不想把它放在模板中。
具有计算属性的TS 类的示例:
class Person {
firstName: string;
lastName: string;
fullName: string;
constructor (firstName: string, lastName: string) {
this.firstName = firstName;
this.lastName = lastName;
this.fullName = firstName + ' ' + lastName;
}
}
let person = new Person('John', 'Doe');
console.log(person.fullName); // => John Doe
Run Code Online (Sandbox Code Playgroud)
该示例使用getter:
class Person {
firstName: string;
lastName: string;
constructor (firstName: string, lastName: string) {
this.firstName = firstName;
this.lastName = lastName;
}
get fullName(): string {
return this.firstName + ' ' + this.lastName;
}
}
let person: Person = new Person('John', 'Doe');
console.log(person.fullName); // => John Doe
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6180 次 |
| 最近记录: |