如何访问实例上的静态成员

How to access static member on instance?

本文关键字:实例 静态成员 访问 何访问      更新时间:2023-09-26

这是代码,我已经为此苦苦挣扎了几个小时,想法是跟踪创建了多少实例,但也使调用静态方法和更改/更新静态成员成为可能。有类似的问题,但我无法为我的问题实施任何解决方案。

  // object constructor
function Foo() {
    this.publicProperty = "This is public property";
}
// static property
Foo.staticProperty = "This is static property";
// static method
Foo.returnFooStaticProperty = function() {
    return Foo.staticProperty;
};

console.log("Static member on class: " + Foo.staticProperty); // This is static property

console.log("Result of static method: " + Foo.returnFooStaticProperty()); //This is static property
var myFoo = new Foo();
console.log("myFoo static property is: " + myFoo.staticProperty); // undefined

为了简单起见,我在这里更改了构造函数和成员名称。我认为发生的事情是显而易见的。我希望构造函数对象和实例共享相同的静态属性。

我可以访问构造函数对象上的静态成员,但在实例上我未定义。

您可以尝试通过构造函数访问静态属性

console.log(myFoo.constructor.staticProperty);

编辑:我重新阅读了您的问题,这段代码解决了您的实际问题,如前所述:

JavaScript:

function Foo() {
    this.publicProperty = "This is public property";
    Object.getPrototypeOf(this).count++;
}
Foo.prototype.count = 0;
console.log(new Foo().count, new Foo().count, Foo.prototype.count);

如果释放对象以进行垃圾回收,这不会自动减少计数,但您可以使用删除然后手动递减。

Javascript是基于原型的。换句话说,对象的所有实例共享相同的原型。然后,您可以使用此原型放置静态共享属性:

function Foo() {
  this.publicProperty = "This is public property";
}
Foo.prototype.staticProperty = "This is static property";
var myFoo = new Foo();
console.log(myFoo.staticProperty); // 'This is static property'
Foo.prototype.staticProperty = "This has changed now";
console.log(myFoo.staticProperty); // 'This has changed now'

非常简单的方法:

class MyClass{
   static t
   constructor(){
      MyClass.t=this;
   }
   my1stMethod(){
      new SomeOtherClass( somevalue, function(){
        // now, here 'this' is a reference to SomeOtherClass so:
            MyClass.t.my2ndMethod();
    })
   }
 
   my2ndMethod(){
      console.log('im my2ndMethod');
      this.my3dMethod();
   }
   my3dMethod(){
      console.log('im my3dMethod');
   }
}