在不使用类的实例的情况下访问javascript类的静态属性

时间:2016-12-28 05:55:19

标签: javascript class static

我试图访问类的静态属性而不使用类的实例来执行此操作。我尝试在this post中调整方法,但无济于事。我得到的只是test.getInstanceId is not a function

根据我如何创建课程(如下),我该怎么做? Here is a fiddle

test = (function() {
  var currentInstance;

  function test() {
    this.id = 0;
    currentInstance = this;
    // this won 't work
    this.getInstanceId = function() {
      return currentInstance.id;
    }
  }


  test.prototype.setId = function(id) {
    this.id = id;
  }

  return test;
})();


var myTest = new test();
myTest.setId(1);
console.log(myTest.id)
console.log(test.getInstanceId());

2 个答案:

答案 0 :(得分:0)

正如我的评论所示,您使用的是test.getInstanceId()而不是myTest.getInstanceId()

var test = (function() {
  var currentInstance;
  /* This won't work
  function getInstanceId(){
      return currentInstance.id;
  }
  */

  function test() {
    this.id = 0;
    currentInstance = this;
    // this won 't work
    this.getInstanceId = function() {
      return currentInstance.id;
    }
  }


  test.prototype.setId = function(id) {
    this.id = id;
  }

  return test;
})();


var myTest = new test();
myTest.setId(1);
console.log(myTest.id)
console.log(myTest.getInstanceId());

Fid:https://jsfiddle.net/gt0wd8hp/10/

答案 1 :(得分:0)

感谢RobG,下面的代码可以使用。它通过使用test.currentInstance = ...设置变量使变量公开。这是the working fiddle

在检查对象test时,现在公共变量currentInstance似乎在test函数原型之外“活”,我没有意识到这是可能的。

更正了他指出的命名惯例 - 它应该是Test而不是test。

test = (function() {
  test.currentInstance = undefined;

  function test() {
    this.id = 0;
    test.currentInstance = this;
  }


  test.prototype.setId = function(id) {
    this.id = id;
  }

  return test;
})();



var myTest = new test();
myTest.setId(1);
console.log(myTest.id)
console.log(test.currentInstance.id);