[英]TypeScript function inheritance
I don't even know if this is possible in TypeScript, but I'm trying to inherit a function from a Class, like this: 我甚至不知道TypeScript中是否可以这样做,但我试图从类继承一个函数,如下所示:
import {Component, AfterViewInit, ElementRef} from 'angular2/core';
@Component({})
class Class1 {
name: string;
constructor(private el: ElementRef) {}
private setName() {
this.name = "test";
}
ngAfterViewInit() {
this.setName();
}
}
@Component({
selector: 'test'
})
export class Class2 extends Class1 {
ngAfterViewInit() {
super.ngAfterViewInit();
console.log(this.name);
}
}
but I'm getting the following error in console when calling the setName() function: 但是在调用setName()函数时我在控制台中收到以下错误:
EXCEPTION: TypeError: this.el is undefined
EXCEPTION:TypeError:this.el未定义
Why isn't this working? 为什么这不起作用?
Constructors are not inherited.
构造函数不是继承的。
They are. 他们是。 Following sample shows this:
以下示例显示:
class Parent {
constructor(foo:number){}
}
class Child extends Parent {
}
const child1 = new Child(); // Error!
const child2 = new Child(123); // OKAY!
However they are not analyzed for dependency injection. 但是,他们没有分析依赖注入。 This means that your child class constructor isn't called with the same parameters as expected by the parent (in your case `el).
这意味着您的子类构造函数不会使用父项所期望的相同参数调用(在您的情况下为el)。 You need to specify all the DI elements on each child class.
您需要在每个子类上指定所有DI元素。 So by chance the correct code is the one from the accepted answer:
因此,正确的代码是接受答案的代码:
@Component({
selector: 'test'
})
export class Class2 extends Class1 {
constructor(el: ElementRef) {
super(el);
}
}
Constructors are not inherited. 构造函数不是继承的。 You need to define them in each subclass
您需要在每个子类中定义它们
@Component({
selector: 'test'
})
export class Class2 extends Class1 {
constructor(el: ElementRef) {
super(el);
}
ngAfterViewInit() {
super.ngAfterViewInit();
console.log(this.name);
}
}
Consider updating el
's scope to protected
, meaning it can be accessed by both the class where it's declared and any derived classes. 考虑将
el
的范围更新为protected
,这意味着它可以被声明它的类和任何派生类访问。
// before
constructor(private el: ElementRef) {}
// after
constructor(protected el: ElementRef) {}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.