#286 enhancement
ronin-28987 (at lighthouseapp)

Construct a class with arbitrary number of arguments

Reported by ronin-28987 (at lighthouseapp) | August 16th, 2008 @ 04:45 PM | in 1.7

Adding the next piece of code to Class.Methods will make it possible to construct a class with an arbitrary number of arguments.


Class.Methods = {
  addMethods: function(source) {
    // ...
  },

  construct: function(args) {
    var init = this.prototype.initialize; // store original initialize
    this.prototype.initialize = Prototype.emptyFunction; // temporary empty initialize
    var instance = new this(); // create instance
    instance.initialize = this.prototype.initialize = init; // restore initialize
    instance.initialize.apply(instance, $A(args) ); // apply initialize
    return instance; // return new object
  }
};
// ------
// now we can use:
var someInstance = SomeClass.construct(["arg1", "arg2"]);

This can be very useful when you have "factory"-methods in which you don't need to know the number of arguments, as in:


function createClass(className) {
  var args = $A(arguments); args.shift();
  return window[className].construct(args);
}

Comments and changes to this ticket

Please Sign in or create a free account to add a new ticket.

With your very own profile, you can contribute to projects, track your activity, watch tickets, receive and update tickets through your email and much more.

New-ticket Create new ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile ยป

The Prototype JavaScript library.

Shared Ticket Bins

People watching this ticket

Pages