Martin Pecka
Martin Pecka

Reputation: 3083

Define object's methods before its constructor in Javascript?

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

Answers (3)

Teemu
Teemu

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

Eran Boudjnah
Eran Boudjnah

Reputation: 1278

Try delaying setting the prototype methods to after the document is ready.

Upvotes: 0

Jacob Lauritzen
Jacob Lauritzen

Reputation: 2850

It is not possible to alter a prototype of a not-yet-defined object.

Upvotes: 0

Related Questions