繁体   English   中英

是否可以在ES6中的类的静态方法中访问变量和函数?

[英]Is it possible to access variables and functions inside static methods of class in ES6?

首先,将解释我的查询的代码

class myClass {
    constructor() {
        this.myVariable = 10; 
    }

    myFunctionCalledFromStaticFunction() {
        console.log (`myFunctionCalledFromStaticFunction myvariable is ${this.myVariable}`);
    }

    static staticMyFunctionTwo() {
        console.log (`staticMyFunctionTwo myvariable is ${this.myVariable}`);
        this.myFunctionCalledFromStaticFunction();
    }

    static staticMyFunction() {
        console.log (`staticMyFunction myvariable is ${this.myVariable}`);
        myClass.staticMyFunctionTwo();
    }

    myFunctionTwo() {
        console.log (`myFunctionTwo myvariable is ${this.myVariable}`)
        myClass.staticMyFunction();
    }

    myFunction() {
        console.log (`myFunction myvariable is ${this.myVariable}`)
        this.myFunctionTwo();
    }
}

(function ($) {
    'use strict';
         const helloClass = new myClass();
         console.log (`main myvariable is ${helloClass.myVariable}`)
       helloClass.myFunction();  
       myClass.staticMyFunctionTwo();
}(jQuery));

而且,现在是一个codePen示例https://codepen.io/hellouniverse/pen/jYyYre

现在,我不得不放弃一个免责声明。 我搜索了stackoverflow,在线和我自己的经验。 我很确定这是不可能的

如果您获取代码并运行它或签入代码笔,则会注意到myVariable在静态函数中未定义。 另外,我不能从静态函数调用普通函数。

我的陈述正确吗? 还是可能或有解决方法?

我假设您希望通过静态和非静态方法都可以访问原始数据。 在这种情况下,您宁愿使用Symbolconst

如何使用符号,您可以在此处阅读: MDN符号

以及修改后的示例: 使用Symbol使用const关键字

查看您的代码笔,答案是否定的,您不能在静态函数调用中使用this ,除非您正在调用另一个静态方法。 正如MDN所指出的那样, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static ,您可以使用它

class Logger {
    static error(message) {
        this.log(message, 'error');
    }

    static log(message, level) {
        console[level](message);
    }
}

您必须了解类方法的适用范围。 考虑

class Foo {
  static bar () {
    console.log(this.fooProp);
  }
};

大致相同:

function Foo() {};
Foo.bar = function () { console.log(this.fooProp); };

请注意,它不是Foo.prototype.bar 函数是在JavaScript对象,就像任何其他物体,当你调用对象的方法(如Foo.bar()那么this被设置为它被称为上(如函数“富”的对象,而不是一个实例Foo)。 我可以说

Foo.fooProp = 3;
Foo.bar(); // logs 3

从未实际创建Foo的实例。 我也可以从实例中调用它

let foo = new Foo();
foo.constructor.bar(); // logs 3

但是, this值将始终引用类/构造函数而不是实例

foo.fooProp = 5;
foo.constructor.bar(); // still 3

除非有人这样​​做:

Foo.bar.call(foo); // now it's 5

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM