typescript 错误 : An outer value of 'this' is shadowed by this container

标签 typescript class oop

我在 Typescript 类方法声明中有一个错误,但我不明白错误消息是如何与错误相关联的。

消息似乎在说“this”是any类型,但我们在类定义中,所以我认为“this”非常清楚。

有人可以解释错误消息与错误的关联吗?

原始方法:

calcSize = function() {
    return this.width * this.length; // Error on this line
};

// Error text: 'this' implicitly has type 'any' because it does not 
//have a type annotation.ts(2683)
//app.ts(39, 16): An outer value of 'this' is shadowed by this container.

修复:

calcSize() {
    return this.width * this.length;
};

完整上下文(固定):

class BaseObject {
    constructor(
        public width: number = 0,
        public length: number = 0
        ) {}

};

class Rectangle extends BaseObject {

    constructor(public width: number = 0, public length: number = 0) {
        super(width, length);
    }

    calcSize() {
        return this.width * this.length;
    };
}

最佳答案

在 TypeScript(和 ES6)中存在两种函数:经典的函数声明和箭头函数。经典函数声明具有 this 关键字的默认 float 绑定(bind)逻辑 - 箭头函数将不断使用包含箭头函数的上下文的 this 值。在示例中,这将是周围类的实例。

class Rectangle extends BaseObject {
  // ..
  calcSize = function() {
    // The keyword "function" will cause "this" to be floating.
    // Since the function is explicitly assigned to calcSize
    // (older) TypeScript may not infer the type of "this".
    // The value of "this" can be re-bound by changing the context
    // using bind or call.
    // -> Value of "this" defaults to the class instance
    return this.width * this.length; // (potential) type Error on this line
  };

  calcSizeAsMember () {
    // This is also a classic function which will use floating binding
    // therefore "this" will be the type of the containing class.
    // The value of "this" can be re-bound by changing the context
    // using bind or call.
    // -> Value of "this" defaults to the class instance
    return this.width * this.length; 
  };

  calcSizeAsArrowFunction = () => {
    // This is an arrow function which has a constantly-bound "this" keyword, 
    // it is not possible to re-bind afterward.
    // The type of "this" is always the type of the containing class.
    // Changing the context using bind or call will have no effect
    // -> Value of "this" is always the class instance
    return this.width * this.length;
  };

};

关于 typescript 错误 : An outer value of 'this' is shadowed by this container,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56204346/

相关文章:

在 Netbeans 中找不到类错误

c++ - 类对象的模板

c++ - 从子构造函数(模板)访问父成员

c++ - 从基类扩展功能的派生类的最佳设计

html - 对模板组件中的 ng-content 使用样式

reactjs - 使用 React 的 useState 钩子(Hook)时输入可空状态的正确方法

java - getResourceAsStream 方法之间的区别

java - 反射调用方法还是使用继承的固定方法?

less - LESS 和 Typescript 中的常量

typescript - ExpectedConditions 在 Protractor 中未定义