Javascript Static Inheritance
Solution 1:
How do I get MultiPage to inherit the static members of Tool
This is impossible. A function can only inherit from Function.prototype
, and nothing in between.
However, there is no need to do that. JavaScript is no class-based language, and there is a better solution for your actual problem. You haven't told us about your usecase yet, but standard solutions would be putting the property on the prototype
object or just accessing it as Tool.datacontext
even from a Multipage
.
Solution 2:
If you want to inherit static members, there's nothing for it but to copy the properties of Tool onto MultiPage. It's easy enough with jQuery or Underscore:
$.extend(MultiPage, Tool);
_.extend(MultiPage, Tool);
You can easily make your own extend
if you don't want to add any utility libraries:
function extend(target, source) {
for(var key insource) {
if (source.hasOwnProperty(key) && key !== 'prototype') {
target[key] = source[key];
}
}
}
The reason you can't simply inherit static properties is that constructor functions cannot themselves have an internal class other than Function
. So a constructor function's prototype
(not its own prototype
property, but the Function.prototype
which directly extends the constructor function object) is always Function.prototype
, shared amongst every function under the same global scope.
Update
As of 2016, major browsers support Object.setPrototypeOf. However, as you can see in the linked documentation, this function breaks all kinds of engine optimizations. I do not recommend using this, since you can usually structure your program to avoid its drawbacks.
Post a Comment for "Javascript Static Inheritance"