Search code examples
javascriptjqueryruby-on-railsruby-on-rails-3.1prototype-programming

How to change Prototype class declarations into jquery?


I'm working with my Rails 3.1 migration and it's getting harder and harder to keep jquery and prototype living peacefully side by side. I'm investigating a way to change my Prototype-way implemented js-files into jquery format.

I've used heavily prototype-way of declaring classes and sub-classes:

// properties are directly passed to `create` method
var Person = Class.create({
  initialize: function(name) {
    this.name = name;
  },
  say: function(message) {
    return this.name + ': ' + message;
  }
});

// when subclassing, specify the class you want to inherit from
var Pirate = Class.create(Person, {
  // redefine the speak method
  say: function($super, message) {
    return $super(message) + ', yarr!';
  }
});

var john = new Pirate('Long John');
john.say('ahoy matey');
// -> "Long John: ahoy matey, yarr!"

I've read about John Resig's script: http://ejohn.org/blog/simple-javascript-inheritance/. Is this the way to go? Or should I choose some other approach?

I have about 15 js-files (one class per file). I'm willing to spend some time for this migration, so I'd like to do it right. Thanks for your professional help!


Solution

  • Here's one possible way to implement your example with plain functions.

    function Person(name) {
      this.name = name;
    }
    
    Person.prototype.say = function (message) {
      return this.name + ": " + message;
    };
    
    function Pirate(name) {
      this._super = Person.prototype;
      this._super.constructor.apply(this, arguments);
    }
    
    Pirate.prototype.say = function (message) {
      return this._super.say.apply(this, arguments) + ", yarr!";
    };
    
    john = new Pirate("Long John");
    john.say("ahoy matey");
    

    You'd probably want to extract the inheritance operations into a function, but this gives you the basic idea.