Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to give javascript partial class behavior like C# or monkey patching like Ruby does?

The idea behind partial classes is that you can group certain functions together. The best example of this in C# is putting control definitions in one file and the event handlers in another. In Ruby, you can use Monkey patching to replace entire functions etc to get code to do something you want it to.

I haven't found a reason to do this yet, but I figure as web improves, more of an application is going to be on the client side so I'm wondering if some of the great features I find in server-side languages, I can also use in Javascript.

Does anyone know?

like image 823
aarona Avatar asked Dec 12 '22 13:12

aarona


2 Answers

// file 1

function augment() {
    this.monkey = "monkey";
}

// file 2

function augmentMore() {
    this.patch = "patch";
}

// file 3

var o = {};
augment.call(o);
augmentMore.call(o);
console.log(o.monkey + o.patch);

Monkey patching works. partial classes can work by convention. For example consider this convention.

// file main
function SomeObject() {
    for (var i = 0, ii = SomeObject.Partial.length; i < ii; i++) {
         SomeObject.Partial[i].apply(this, arguments);
    }
}

SomeObject.Partial.SomeName = function() {
   ...
}

// file extra
SomeObject.Partial.SomeOtherName = function() {
   ...
}

JavaScript is surprisingly powerful. Was there a specific example you were looking for?

like image 111
Raynos Avatar answered Dec 25 '22 23:12

Raynos


If such a split makes real sense then you can do this:

File #1

function MyObjectType() { this.init(); }

File #2

MyObjectType.prototype.init = function() { this.one = 1; }

File #3

MyObjectType.prototype.onClick = function() { if(this.one == 1) alert("I am so alone..."); }

And somewhere else you can use it as:

var myObject = new MyObjectType();
myObject.onClick();

Welcome to prototype yet kinda functional programming world!

like image 39
c-smile Avatar answered Dec 25 '22 23:12

c-smile