angularjs - Làm thế nào để tính toán một thuộc tính trên một lớp trong typescript?
Trong javascript tôi sẽ làm nó như thế này:
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}
Nhưng tôi chưa thể tìm ra cách nào để làm điều đó trong TypeScript. Không cái nào trong số này hoạt động:
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")};
}
Tôi khởi tạo nó như thế này:
somevar: A = {
foo: 1,
bar: 2
}
Ngoài ra tôi đã thử cái này:
somevar: A = {
foo: 1,
bar: 2,
this.yep: this.foo + this.bar
}
Cảm ơn bạn đã giúp đỡ. Phép toán này sẽ khó hơn và tôi sẽ cần nó nhiều hơn một lần, vì vậy tôi không muốn đưa nó vào mẫu.
Câu trả lời #1
Ví dụ về lớp TS với một thuộc tính tính toán:
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
Ví dụ sử dụng 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
Câu trả lời #2
A là một class chứ không phải interface, vì vậy bạn cần phải tạo một thể hiện. Bạn không thể chỉ gán một đối tượng literal. Không chỉ đủ để "hình dạng" tương thích; nó phải là một thể hiện của class.
Các biến được khai báo với private, protected hoặc public trong constructor sẽ được thêm vào lớp.
Ví dụ:
class A {
public yep: number;
constructor(
public foo: number, // will be transpiled in the constructor to: this.foo = foo;
public bar: number // will be transpiled in the constructor to: this.bar = bar;
) {
this.yep = foo + bar;
}
}
const a: A = new A(1, 2);
