访问es2015类函数成员

Access es2015 class function member

本文关键字:成员 类函数 es2015 访问      更新时间:2023-09-26

'use strict';
class Test {
    lorem () {
    }
    static ipsum () {
    }
}
console.log(Test.lorem); // undefined
console.log(Test.ipsum); [Function]

有没有办法访问Test.lorem?我试过Test.prototype.lorem和Test.lorem,但都返回未定义的结果。

我想测试的函数的构造函数做了一些类似构造函数的事情,所以在单元测试中,我只想直接从类中运行函数。

有什么想法吗?

该方法在prototype中可用。

Test.prototype.lorem

但是,请记住,直接调用此方法意味着this将不会引用对象的实例。

Test.lorem未定义,因为它不是静态方法。将非静态方法添加到prototype对象中。

证据汇编自Babel 6与ES2015预设。

'use strict';
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Test = (function () {
    function Test() {
        _classCallCheck(this, Test);
    }
    _createClass(Test, [{
        key: 'lorem',
        value: function lorem() {}
    }], [{
        key: 'ipsum',
        value: function ipsum() {}
    }]);
    return Test;
})();
console.log(Test.prototype.lorem);

除非是静态成员,否则不应该在没有实例的情况下执行方法。

在大多数(如果不是全部的话)面向对象语言中,这是一个非常基本的概念。

如果您只想获得函数的引用,那么使用类原型确实可行。

顺便说一句,实际上可以在没有实例的情况下执行方法,因为JavaScript确实允许这种灵活性,但您应该避免这种做法。

您需要一个Test的实例。

class Test {
      lorem () {
        console.log('test');
      }
      static ipsum () {
      }
  }
  var test = new Test();
  test.lorem();

或者你可以做

Test.prototype.lorem();

不确定为什么我得到了-1,但有

类方法在ES2015中是不可枚举的

不能直接访问非静态的类成员。

https://phabricator.babeljs.io/T959