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

时间:2017-12-27 00:11:55

标签: javascript ecmascript-6

首先是解释我的查询的代码

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在静态函数中是未定义的。另外,我无法从静态函数调用正常函数。

我在这些陈述中是否正确?或者是否可能或有解决方法?

3 个答案:

答案 0 :(得分:2)

我假设您希望在静态和非静态方法中拥有可访问的原始数据。对于此类情况,您宁愿使用Symbolconst

如何使用符号,您可以在此处阅读:enter image description here

您修改过的示例:MDN Symbolusing Symbol

答案 1 :(得分:1)

查看您的codepen,答案是否定的,您不能在静态函数调用中使用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);
    }
}

答案 2 :(得分:0)

您必须了解类方法的用途。考虑

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

或多或少与此相同:

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

请注意,它不是Foo.prototype.bar。函数是JavaScript中的对象,就像调用对象方法时的任何其他对象一样(例如Foo.bar()),然后将this设置为调用它的对象(例如函数&#39) ; Foo', 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