質問

The differences between 'instance members' and shared 'class' members are obvious to me, as are the times to use one or the other. But I've recently come across the concept of 'static members', which in Javascript are simply methods / properties on the constructor itself, unavailable to any instances via this. For clarity's sake, here's what I'm talking about:

var Constructor = function() {

  // Private instance members
  var private = 'I am private';

  // Public instance members
  this.public = 'I am public';

};

// Shared class members
Constructor.prototype.shared = 'I am shared';

// So-called 'static' member
Constructor.static = 'I am static';

var f = new Constructor();
f.private; // undefined
f.public; // 'I am public'
f.shared; // 'I am shared'
f.static; // undefined

Like I said, the purpose of and delineation between the first three are obvious. When, however, should one use static members? When is Foo.bar() ever better than just making it a shared method of the class: Foo.prototype.bar()?

I understand the prototype chain, so the obvious difference is that static members aren't part of the prototype chain of the instances -- which I guess may matter in some applications. But that's not the question. The question is, what is one (or more) good, real-world examples for creating such 'static members'?

役に立ちましたか?

解決

what is one (or more) good, real-world examples for creating such 'static members'?

There are some good examples in the language itself. For example (there are a lot more than these two as well):

Array.isArray([]); // true
Object.keys(someObj); // Returns array of key identifiers

Static properties are useful for providing functionality associated with a "type" (array or object in the examples above) that doesn't depend on an instance.

他のヒント

Static properties are good for when you need a value that is common among all instances of the object. As a trivial example, you could have Constructor.numberOfTimesInstantiated which you increment by one each time new Constructor is called.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top