In JavaScript, you can get class-like behavior by defining functions like this:
var Video = function() { var self = this; // init code here this.num = 2; this.getNum = function() { return self.num; }; };
Or like this:
var Video = function() { // init code here this.num = 2; }; Video.prototype.getNum = function() { return this.num; };
I like the second way better, but the first style works as well. ES6 has a standard way to define classes, see https://github.com/addyosmani/es6-equivalents-in-es5#classes, but I'm only talking about ES5.
I ran across some code in
SherdJS
that defines a class using the first method I mentioned, and also did some
interesting things that I hadn't seen before. Notice how, in
youtube.js, a new function is defined at
this.microformat.create()
. That confused me, because what is
this.microformat
? Digging further, you notice that
Sherd.Video.YouTube
is a child class of a few other classes.
You can find this.microformats
in
video.js, and it's a plain JS object with a bunch of
functions in it. JavaScript is known for its flexibility in allowing you
to write confusing code. But this particular pattern could be
implemented in Python as well:
class Video: microformats = { 'create': (lambda x: return ''), 'find': (lambda html_dom: return [{'html': html_dom}]), # etc... }
But why would you do that? Because these functions don't depend on any
instance data, why are they even in the Sherd.Video
class?
However, the YouTube
class overrides
this.microformats.create()
with instance data. I found
this confusing, maybe because it's unexpected. I think
this.microformats
is unnecessary, and if YouTube
needs to create a microformat, it can just define a
createMicroformat()
method.