簡體   English   中英

具有擴展類和模塊的es6變量范圍

[英]es6 variable scope with extended class and modules

為什么es6不允許這樣做? 我知道該消息僅在警報模塊中定義,而在基本模塊中未定義,但是我(顯然是錯誤的)想像一下,由於警報類可以訪問它,因此所有類都應該...有想法嗎?

//file component.js
import Base from './base';
const message = "hello";
class Alert extends Base {
    initialize() {
        this.render();
    }
}
export default Alert;

//file base.js
class Base {
    render() {
        alert(message);
    }
}
export default Base;

Base類及其方法無法訪問component模塊中的任何變量,該模塊具有自己的作用域。 如果它將導入模塊,則可以訪問導出的值,但不能訪問本地message變量。

我認為您將要在此使用該類的靜態屬性,在Alert實例上調用Base方法時, Base方法將可以訪問這些屬性:

import Base from './base';
export default class Alert extends Base {
    initialize() {
        this.render();
    }
}
Alert.message = "hello"; // not constant, though; you'd need to use
                         // Object.defineProperty(Alert, "message", {value: …} for that

export default class Base {
    render() {
        alert(this.constructor.message);
    }
}
Base.message = "";

有關this.constructor.…工作方式 ,請參見es6調用靜態方法

這不起作用,因為JavaScript具有詞法范圍 ,而不是動態范圍。

詞法作用域意味着變量是否可訪問取決於變量在源文本中的位置 ,而不取決於運行時信息。

簡化示例:

function foo() {
  var bar = 42;
  baz();
}

function baz() {
  console.log(bar); // error because bar is not in the scope of baz
}

注意:對於類或ES6,這並不是新問題,總是如此。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM