Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
406 views
in Technique[技术] by (71.8m points)

monkeypatching - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
// 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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...