There seems to be quite a few techniques out there for creating client side objects. What I find really confusing is determining what each technique is called. I've used prototype before
MyObject.prototype.someMethod = function (e, a) {
.....
};
But I've also seen objects created in different like this
MyObject.someMethod = function () {
....
}
What is the second techinque called and why would one use one over the other?
The first example is analogues to defining methods on a class. Every instance of the class uses the same code; this in such a method points to the instance on which the method was invoked.
The second is analogous to defining a static method on a class. You invoke the method like
MyObject.someMethod();
It doesn't make sense to invoke the method on an instance.
I guess you could call the first "prototype methods" and the second "constructor/class methods".
If you are comfortable using classical OO terminology when talking about javascript, which is somewhat awkward as Javascript uses prototypal inheritance, you can call the the first "instance methods" and the second "static methods".
The simplest answer is that using the prototype keyword to define a method on an object will allow that method to be used on all objects which inherit from it.
There are no classes in JavaScript, but you can emulate inheritance through the use of the prototype object (property).
myObject.prototype.method will add a "method" to ALL objects derived from myObject (you can do this to jQuery after jQuery has loaded -- $.prototype.method [$.fn.method] would add a method to all jQuery objects regardless of when they are/were created).
myObject.method will only add a "method" to myObject as it was at the time that line of code was executed (a static method). Any myObject invoked before this line executes will not have access to "method".
Javascript uses what's called Prototypical Inheritance to implement inheritance of traits. Consider the following example:
Superclass = function() {
//constructor code
}
Superclass.prototype.toString=function() {
return "Derp!";
}
Superclass.derp= function(){return 'herp!'}
var instance = new Superclass();
instance.toString();//valid
instance.derp();//fails
There are several things going on here.
First, before worrying about defining methods of objects, worry about the creation of objects.
So, there are several ways of creating objects. First, you can just create an inline object, out of the blue:
var obj = { property : "myProperty", func : function () {} };
You now have a brand new object.
You can extend that object by adding to it, after the fact.
obj.property02 = "myOtherProperty";
obj.otherFunc = function () { return this.property02; };
But the downfall of constructing inline objects is that all properties and methods are 100% public.
In order to deal with this, you can have a constructor function which creates and returns an object.
var MakeWallet = function (starting_amount, pin) {
var balance = 0,
wallet = {};
wallet.add = add_balance;
wallet.deduct = deduct_amount;
wallet.amount = check_balance;
return wallet;
function check_balance (pin) { /*...*/ }
function validate_pin (user_pin) { /*...*/ }
function add_balance (amount, pin) { /*...*/ }
function deduct_amount (amount, pin) { /*...*/ }
};
var myWallet = MakeWallet(1, 9274);
What do I get for my trouble?
ALL of the data is tamper-proof.
A user might still be able to rewrite wallet.deduct, but they won't actually get the real value of the pin, or get the amount in the wallet, or get any of the internal functions that I don't want them to have, including any internal security-numbers or entity/serial numbers I want to grant to track the wallet.
That's the benefit of building in this way.
Again, I can add methods and properties to the wallet, afterward:
myWallet.breakItOpen = function () { return this.balance; };
myWallet.stuffIt = function () { balance = 400000000; };
But neither of these things is actually going to have access to the variables or the functions inside of the original myWallet.
Only functions which existed at the time of creation will have access.
In other, more traditional creation-methods, you can use a class-like constructor function, using this.
function MakeWalletClass (starting_amount, pin) {
var balance = 0,
serial_and_pin = generate_serial() + "_" + pin;
this.balance = balance;
this.checkBalance = function () { return this.balance; };
}
var myWalletInstance = new MakeWalletClass(1, 1234);
But there's a problem:
myWalletInstance.balance is public.
Anybody can see it or change it.
Not good.
We could get around that by doing this:
function MakeWalletClass (starting_amount, pin) {
var balance = 0,
serial_and_pin = generate_serial() + "_" + pin;
this.checkBalance = function () { return balance; };
}
var myWalletInstance = new MakeWalletClass(1, 1234);
Now, this.checkBalance is reading the hidden balance variable, and not a publicly editable property.
Now, MakeWalletClass.prototype.
When you use the constructor pattern (ie: a function which adds properties to this and returns this, or doesn't return anything -- it returns this in the background -- and is called with the new keyword), adding prototype properties and methods will add properties and methods which are available to EVERY instance of the object you made.
So if your bank is called "The Bank of Bob", you could add:
MakeWalletClass.prototype.bankName = "The Bank of Bob";
Now every single instance of new MakeWalletClass(); will have a bankName property, and every one will be the exact-same value, and every one will be publicly available.
var yourWalletInstance = new MakeWalletClass(500, 2341);
yourWalletInstance.bankName; // "The Bank of Bob";
The prototype properties are even available on objects that you make before you add the property to the constructor function's prototype.
You can add prototype methods in the same way.
var myWalletInstance = new MakeWalletClass(1, 1234);
MakeWalletClass.prototype.getBalance = function () { return balance; };
myWalletInstance.getBalance(); // undefined;
Whoops!
It doesn't work.
Prototype functions have access ONLY to public properties (anything they can call with this.XXX).
So the upside of adding prototype properties is that they save a lot of memory.
If your program requires 3000 wallets, and you add a prototype function to the constructor, that function only exists 1 time in memory.
The downside of adding the prototype is that it can only do public things, so unless you want to make balance or pin public properties (hint: don't), prototypes are useless for private work.
So for those 3000 wallets, you need 3000 copies of any method that deals with balance or pin.
Now that you've got an understanding of all of that, and what prototype is for... the REAL difference between:
MakeWalletClass.prototype.say_bankName = function () { /*...*/ };
and
MakeWalletClass.say_bankName = function () { /*...*/ };
is that the prototype works on instances (wallet = new MakeWalletClass), and the method of MakeWalletClass doesn't -- it's only useful if you want a function attached to MakeWalletClass.
Maybe you want a function that returns the number of wallets made...
Related
I have seen people take two approaches when they create javascript objects, they sometimes define the prototype functions outside the main object and sometimes they do it inside. Defining the prototype functions inside the object has the advantage of using private variables and functions, what's the advantage of defining it outside?
function something (params) {
this.name = params.name;
this.color = params.color;
_someprivatefunction = function () {};
something.prototype.publicFunction = function () {_someprivatefunction() };
}
As opposed to:
function something (params) {
this.name = params.name;
this.color = params.color;
_someprivatefunction = function () {};
}
something.prototype.publicFunction = function () {//can't call the private function here };
EDIT: as suggested in the comments down below, this is a third option (but the problem with this is now the private function cant access any of the private variables inside the constructor.)
(function () {
function something (params) {
this.name = params.name;
this.color = params.color;
}
_someprivatefunction = function () {};
something.prototype.publicFunction = function () {_someprivatefunction() };
}());
I would assume that a disadvantage to the first approach is that you are running the prototype assignment every time you instantiate a new object. Seems like it would defeat the purpose of using the prototype since it does work on the object for every instance created.
As I think you know, your two code blocks don't offer the same functionality. The first option allows you to call _someprivatefunction() or other private constructor variables and your second does not. So, first you have to decide if that's a requirement or not. Your two options do not offer equivalent functionality.
If you do want access to the private function, then a third option is as follows:
function something (params) {
// initialize data members
this.name = params.name;
this.color = params.color;
// initialize private members
var aPrivateInstanceVar = 4;
// define private function
_someprivatefunction = function () { console.log(aPrivateInstanceVar);};
// define public method with access to private members and functions
this.publicFunction = function () {_someprivatefunction() };
}
This new option will technically work the same as your first option. But (and this might just be my opinion), it feels cleaner. It's assigning a property dynamically to the object at creation time which is a much more common thing to do (just like assigning to this.name and this.color) than assigning something to the prototype at object creation time.
Also, if I came across some uncommented code someone else wrote that has your first construction in it, my first thought would be: "gee, why isn't this assignment to the prototype done once outside the constructor" and I might even attempt to "fix" it without realizing that it needed to be there. But, if I came across the structure I'm proposing, it would like like a perfectly common design pattern and I would not be tempted to "fix" the code (accidentally breaking it in the process).
The other day I was fiddling with Javascript, and I noticed that I can't write a prototype to an object within a prototype function. Like this:
var obj = function() { }
obj.prototype.First = function() {
this.prototype.Second = function() {
alert("Second Prototype");
}
}
obj.First();
obj.Second();
For some reason, the second prototype won't work and the code doesn't run. Is my syntax wrong or are there some prototype limitations that I don't know about? Thanks!
Edit:
I'm not trying to add a prototype to a prototype... that wouldn't make much sense. This is what I'm trying to do: Add two separate prototypes to obj. Prototype 2 is defined when prototype 1 is called. I thought that this would contain a reference to object, so this.prototype would be the same as obj.prototype, but it doesn't work as expected.
This is an old question, but I thought I'd add my two cents.
This code is trying to add functions on 'prototype'. However, this can only be done on the class name. What you have is a variable pointing to an anonymous class. To access the variable of an anonymous variable use 'proto'. The below is the same as your example, except, using proto it is 'successful'. Although, I don't see the benefit of using prototypes like this as the prototype added methods only apply to the anonymous instance 'obj'. http://jsbin.com/zapocamipi/edit?js,console
var obj = function() { }
obj.__proto__.First = function() {
console.log("First Prototype");
this.__proto__.Second = function() {
console.log(this);
}
}
obj.First();
obj.Second();
Maybe this could help you out understanding the role of a constructor function and the prototype.
Depending on what you're trying to do (obj, First and Second doesn't really show your intention) you could do:
A Person has Eyes. This can be done through composition.
An Employer is a Person but a Person is not necessarily an Employer (can be Client or Consultant too). This could be done through inheritance.
A Cat can move. In a Class based language Cat has to implement Movable but in JavaScript you can use mix ins and leave the implementation to the default implementation that Movable provides or override it. JavaScript does not compile time check if you do implement certain things.
If you would like to change the type of the object instance after calling a certain function then it's dangerous to meddle with the prototype because that will affect all instances of that type.
Maybe you should return an instance of another type.
var Customer = function(name) {
this.name=name || 'unknown';
};
Customer.createVipCustomer = function() {
return new VipCustomer(this);
}
var VipCustomer=function(customer){
//re use Customer constructor
Customer.call(this,customer.name);
this.isVip=true;
}
//inherit the protype defined members
VipCustomer.prototype=Object.create(Customer.prototype);
VipCustomer.prototype.constructor=VipCustomer;
VipCustomer.prototype.second=function(){
console.log('this is second');
}
var aCustomer = new Customer('Ben');
//update to VipCustomer
aCustomer = Customer.createVipCustomer(aCustomer);
aCustomer.second();
this.prototype doesn't exist.
If you want to add a property to the instance, use this.
If you want to add a property to the prototype, use Constructor.prototype.
Also, obj is a function (class), not an instance,
You want to create an instance using the new keyword, and you should name the constructor function as UpperCamelCase.
I'm just getting into JavaScript and I'm trying to wrap my head around prototypal inheritance. It appears that there's multiple ways to achieve the same effect, so I wanted to see if there is any best practices or reasons to do things one way over the other. Here's what I'm talking about:
// Method 1
function Rabbit() {
this.name = "Hoppy";
this.hop = function() {
console.log("I am hopping!");
}
}
// Method 2
function Rabbit() {}
Rabbit.prototype = {
name: "Hoppy",
hop: function() {
console.log("I am hopping!");
}
}
// Method 3
function Rabbit() {
this.name = "Hoppy";
}
Rabbit.prototype.hop = function() {
console.log("I am hopping!");
}
// Testing code (each method tested with others commented out)
var rabbit = new Rabbit();
console.log("rabbit.name = " + rabbit.name);
rabbit.hop();
All of these appear to have the same effect individually (unless I'm missing something). So is one method preferred over the other? How do you do it?
When you put a method on the prototype, every instance object shares the same reference to the method. If you have 10 instances, there is 1 copy of the method.
When you do what you did in example 1, every instance object has its own version of the same method, so if you create 10 of your objects, there are 10 copies of the code running around.
Using the prototype works because javascript has machinery for associated a function execution with a instance, i.e. it sets the this property for the execution of the function.
So using the prototype is highly preferred since it uses less space (unless of course, that is what you want).
In method 2, you are setting the prototype by setting it equal to an object literal. Note that here you are setting a property, which I think you don't intend to do, since all instances will get the same property.
In Method 3, you are building the prototype one assignment at a time.
I prefer method 3 for all things. i.e. In my constructor I set my property values
myObj = function(p1){
this.p1; // every instance will probably have its own value anyway.
}
myObj.prototype.method1 = function(){..} // all instances share the same method, but when invoked **this** has the right scope.
Let's look at your examples one at a time. First:
function Rabbit() {
this.name = "Hoppy";
this.hop = function() { //Every instance gets a copy of this method...
console.log("I am hopping!");
}
}
var rabbit = new Rabbit();
The above code will work, as you have said in your question. It will create a new instance of the Rabbit class. Every time you create an instance, a copy of the hop method will be stored in memory for that instance.
The second example looked like this:
function Rabbit() {}
Rabbit.prototype = {
name: "Hoppy",
hop: function() { //Now every instance shares this method :)
console.log("I am hopping!");
}
}
var rabbit = new Rabbit();
This time, every instance of Rabbit will share a copy of the hop method. That's much better as it uses less memory. However, every Rabbit will have the same name (assuming you don't shadow the name property in the constructor). This is because the method is inherited from the prototype. In JavaScript, when you try to access a property of an object, that property will first be searched for on the object itself. If it's not found there, we look at the prototype (and so on, up the prototype chain until we reach an object whose prototype property is null).
Your third example is pretty much the way I would do it. Methods shared between instances should be declared on the prototype. Properties like name, which you may well want to set in the constructor, can be declared on a per-instance basis:
function Rabbit(rabbitName) {
this.name = rabbitName;
}
Rabbit.prototype.hop = function() {
console.log("Hopping!");
}
This is an important issue that is often misunderstood. It depends what you're trying to do. Generally speaking, hvgotcode's answer is right on. Any object that will be instantiated frequently should attach methods and properties to the prototype.
But there are advantages to the others in very specific situations. Read this, including the comments: http://net.tutsplus.com/tutorials/javascript-ajax/stop-nesting-functions-but-not-all-of-them/
There are occasions when method 1 above helps, enabling you to have "private" readable/writable properties and methods. While this often isn't worth the sacrifice in heavily instantiated objects, for objects instantiated only once or a few times, or without many internal assignments, or if you're in a dev team environment with lots of different skill levels and sensibilities, it can be helpful.
Some devs incorporate another good strategy that attempts to bridge some of the shortcomings of the others. That is:
var Obj = function() {
var private_read_only = 'value';
return {
method1: function() {},
method2: function() {}
};
};
// option 4
var Rabbit {
constructor: function () {
this.name = "Hoppy";
return this;
},
hop: function() {
console.log("I am hopping!");
}
};
var rabbit = Object.create(Rabbit).constructor();
console.log("rabbit.name = " + rabbit.name);
rabbit.hop();
When doing prototypical OO using new and constructor functions is completely optional.
As has already been noted, if you can share something through the prototype do so. Prototypes are more efficient memory wise and they are cheaper in terms of instantiation time.
However a perfectly valid alternative would be
function Rabbit() {
// for some value of extend https://gist.github.com/1441105
var r = extend({}, Rabbit);
r.name = "Hoppy";
return r;
}
Here your extending "instances" with the properties of the "prototype". The only advantage real prototypical OO has is that it's a live link, meaning that changes to the prototype reflect to all instances.
Do some performance testing (declare around 1 milion rabbit variables) . First method will be the most time and memory consuming.
I'm building a system, with similar details as this question: Can I have different copies of a static variable for each different type of inheriting class
Except it's in JavaScript!
I'm going to have a set of subclasses. Each subclass will have a lot of instances created of it during the life of the program. Each instance of a particular subclass will have different values, except for a file that is common to all. I don't want each instance to have a copy. I want it static (one copy for all). Each different subclass uses a different file though. I want each subclass to inherit the FACT that it HAS a file from a superclass.
EDIT: Quick Summary:
goal: create a class that is a constructor that
constructs the definition of a
subclass, allowing a variable:
- Appearing in every subclass
- Unique to a particular subclass
- Shared by all instances of a particular subclass (one copy for all)
Attempt at illustrating this in code:
var instance1ofSubclass1 = {
staticVar:"SAMEVAL_1", // For brevity I'm showing how staticVar is
// the same. It's notsupposed to be public.
uniqueVar:"adsfasdf"
};
var instance2ofSubclass1 = {
staticVar:"SAMEVAL_1",
uniqueVar:"zxbvczbxc"
};
var instance3ofSubclass1 = {
staticVar:"SAMEVAL_1",
uniqueVar:"qwrtytry"
};
var instance1ofSubclass2 = {
staticVar:"SAMEVAL_2", //<--notice the static var is different
// between subclasses
uniqueVar:"oipoiuu"
};
var instance2ofSubclass2 = {
staticVar:"SAMEVAL_2",
uniqueVar:"hljkhlj"
};
var instance3ofSubclass2 = {
staticVar:"SAMEVAL_2",
uniqueVar:"bnmbmbmnm"
};
My class definitions could go like this:
var subclass1 = (function () {
var staticVar = "SAMEVAL_1"
return function (unique) {
return {
uniqueVar:unique
};
};
}());
var subclass2 = (function () {
var staticVar = "SAMEVAL_2" //<-- different static variable
return function (unique) {
return {
uniqueVar:unique
};
};
}());
Now, I want to go a step further and make a superclass for these classes. That's where I'm stuck. I don't want to have a staticVar definition in every subclass. I want to get it from the superclass.
First of, the compiler will never be able to prevent you from forgetting something since there is no compiler. That's something we'll have to live without.
My suggestion for you would be to use prototyping for this. If the prototype of the superclass contains your variable, the same instance will be used for all the subclasses. And you wont have to repeat yourself in your subclass-files. Static and inherited, so to speak.
MySuperClass.prototype.myStaticVar = "giantFile";
The downside of this solution is that the variable won't really be private. On the other hand, do you really, really need it to be private?
The concept of privacy is a little funny anyhow. In C/C++ everything (private stuff too) can be accessed by pointer-magic. In C# you can use reflection to alter private variables. Nothing is ever really private. JavaScript is even funnier since the scripts in the browser can be altered by the end-user himself! In my opinion, hiding in plain sight is the way to go in this case. Name your variable appropriately (for example, add an underscore or two the beginning of it's name to signify "privacy").
if i'm reading this right, I had a similar issue that you did. Check this SO question that i posted a few weeks ago.
to take that a step further, my .add() method checks to see if the passed in namespace has a supr object attached to it, if not, then it appends the base object called supr to that namespace so that it can have easy access to the root.
I think I've figured it out.
Fiddle: http://jsfiddle.net/zXMaM/
The pattern I've created sends a class definition through another function (essentially the super class) that creates an additional closure for the necessary private static variables and at the same time augments the object created by the class passed in to access the private static variables.
It's hard to explain as this is new to me too, but hopefully between the code and my comments it is followable.
The "superclass" method:
var superClass = function (yourPrivateStaticVar, classDef) {
var privateStatic = yourPrivateStaticVar;
return function () { // return a new constructor (only invoked when a new
// instance is created!)
// run the constructor, grab the object it creates
var newObj = classDef();
// now, augment the object created (these vars/methods have no
// knowledge of the subclass!)
//add private vars/methods to the object
function getPrivStatic() {
return privateStatic;
}
var example_inherited_private_var;
//add public vars/methods to the object
newObj.getPrSt_directly = function () {
return privateStatic;
}
newObj.getPrSt_throughPrivateFunc = function () {
return getPrivStatic();
}
newObj.example_inherited_public_var = "something";
//return the augmented object (a new *instance* of the subclass)
return newObj;
};
};
Defining a "subclass":
//pass the definition of subclass1 through the superclass method and get it back
var subClass1 = superClass("yourChosenPrivateStaticValue", function () {
//private variables/methods go here
return { //this is the actual instance object
//public variables/methods go here
};
});
Again, the fiddle: http://jsfiddle.net/zXMaM/
Let me explain, this is about displaying class source code in IDEs. I have always only one class per file. A class is declared like this in the file mod1.js:
MYGLOB.MOD1.ClassXy = function () {
//constructor, do somothing
}
MYGLOB.MOD1.ClassXy.prototype.memberfunc1 = function () {
//member function 1, do somothing
}
(There are many more functions like memberfunc1 in the real class.)
But in different IDEs and editors the width of the function list is now very large. I want the function lists to display only the last part of the function name (the function name itself).
How about this:
ClassXy = function () {
//constructor, do somothing
}
memberfunc1 = function () {
//member function 1, do somothing
}
MYGLOB.MOD1.ClassXy = ClassXy;
MYGLOB.MOD1.ClassXy.prototype.memberfunc1 = memberfunc1;
It displays nice in the function list. It does not disturb that there are the 2 long assignments at the bottom of the file. But I have the global namespace polluted. How to do this without affecting the global namespace with the global "ClassXy" and "memberfunc1"? (MYGLOB.MOD1.ClassXy is fine.)
Can I do this with parens / closures somehow or what do you suggest? And keep the effect of having the clean function list in the IDE, at least the first part of the function list showing me the member function with their short names?
Please don't suggest different IDEs or editors, this is not about choosing a different code editor, please open a different question on your own if you want to discuss that. This question is about javascript and classes.
Maybe this is a simple thing, but I am quite new to javascript.
It will depend a bit on the capabilities of the editors you're using, but the module pattern can be useful for this (and for avoiding global namespace pollution in general). I'll start the answer assuming you're doing this when defining your classes (objects, really), but there's a note at the end about using shorthand aliases when consuming classes (objects) as well.
Basic example of module pattern
var MYGLOB.MOD1.ClassXy = (function() {
// Define your constructor function
function ClassXy() {
}
// Define your member functions
function memberfunc1() {
}
// Put your member functions on the prototype
ClassXy.prototype = {
memberfunc1: memberfunc1
};
// Return the constructor function to assign it to the MYGLOB.MOD1 object
return ClassXy;
})();
There I replaced the prototype; you may want to just add to it instead, in which case I suggest having a utility function somewhere that does a shallow property copy:
function shallowCopy(dest, src) {
var name;
for (name in src) {
// Depending on your needs, you may want to check
// src.hasOwnProperty(name) here and only copy it
// when that's true
dest[name] = src[name];
}
}
And then replacing the assignment to prototype above with this:
shallowCopy(ClassXy.prototype, {
memberfunc1: memberfunc1
});
Named functions
Amongst other things, using this pattern means you're using named functions rather than anonymous ones. That helps your tools (debuggers in particular) help you. This format creates an anonymous function and assigns it to a property on an object:
MyObject.functionName = function() { ... }; // Not ideal
Whereas if you use the module pattern, you can declare your functions normally and then assign them to properties later (see above); that way they have names that debuggers can show you in call stacks, etc.
Private utility functions
The pattern also provides a nice way of having utility functions (or class-wide data) used by the class without having to make them public at all -- not on the constructor function, not on its prototype, not on instances. For instance, here's the above with a private utility function:
var MYGLOB.MOD1.ClassXy = (function() {
// Define your constructor function
function ClassXy() {
}
// Define your member functions
function memberfunc1() {
// Call our utility function. In this form, be aware that
// within the utility, `this` will *not* be set within
// the utility
utility('bar');
// Alternate form if you want to call `utility` as though it
// were an instance member function; within the utility, it
// can refer to `this` and have it mean the same thing it
// means here in `memberfunc1`
utility.call(this, 'bar');
}
// A utility function. This is entirely private to the class,
// we don't make it a property of anything and so it's never
// visible outside the closure
function utility(foo) {
alert("foo = " + foo);
}
// Put your member functions on the prototype
shallowCopy(ClassXy.prototype, {
memberfunc1: memberfunc1
});
// Return the constructor function to assign it to the MYGLOB.MOD1 object
return ClassXy;
})();
Using a helper
The above may seem a bit clunky at first, but there's no reason you can't create helpers to make it easier to define classes this way. That's what I've done; using my helper I'd define your example like this:
MYGLOB.MOD1.ClassXy = Class.defineClass(function() {
// Takes the place of the constructor function; defining it is
// optional, though, if you don't need to do anything when created
function initialize() {
}
// A member function
function memberfunc1() {
}
// Export our public symbols
return {
initialize: initialize,
memberfunc1: memberfunc1
};
});
You can grab the helper (and the reasoning behind it) from my blog post on the topic.
Consuming long-winded APIs
This same pattern can also be turned on its head, when you want to consume an API that's long-winded: Just define a function, pass in the long-winded things as arguments, and use the argument name instead:
(function(xy) {
// Use the member function; within this closure, xy = MYGLOB.MOD1.ClassXy
xy.memberfunc1();
})(MYGLOB.MOD1.ClassXy);
You can always use an object as a name space. For example, you create an object with short variable name and use it to hold your function. Once ready, you can assign it to your actual production class name.
Fs = new Object();
Fs['ClassXy'] = function() {
this.time = new Date();
alert("From ClassXy: " + this.time);
};
Fs['memberfunc1'] = function() {
alert("From memberfunc1: " + this.time);
};
ClassXy = Fs['ClassXy'];
ClassXy.prototype.memberfunc1 = Fs['memberfunc1'];
const aCX1 = new ClassXy();
aCX1.memberfunc1();
The example code above works.
Hope this helps.