Reputation: 3083
Is it possible to deinfe a class' methods earlier than its constructor in Javascript?
Something like:
MyObj.prototype.fcn = function () {};
MyObj = function () {};
That's because I'd like to separate the instance methods to a different file, but it would be better to load that file earlier than the file with the constructor.
The best solution would be if it would not depend on which file is loaded first.
Thanks in advance.
Upvotes: 0
Views: 54
Reputation: 23416
EDITED
This is the basic implementation of the prototypal inheritance. You can create a constructor and add properties to it in "File 1". Then in "File 2" you can inherit the properties from the early created constructor like this:
// File 1
var Dummy = function () { /* A */}; // Dummy needs to be able to refer globally
Dummy.prototype.methodA = function () {alert(this.constructor);};
// File 2
var BConstructor = function () { /* B */};
BConstructor.prototype = new Dummy(); // Include properties of Dummy too
BConstructor.prototype.methodB = function () {alert(this.constructor);}; // Create more properties if needed
BConstructor.prototype.constructor = BConstructor; // Make sure BConstructor will be the constructor of future-created objects
var a = new BConstructor();
a.methodA();
a.methodB();
Upvotes: 1
Reputation: 1278
Try delaying setting the prototype methods to after the document is ready.
Upvotes: 0
Reputation: 2850
It is not possible to alter a prototype of a not-yet-defined object.
Upvotes: 0