Simple LightWeight OOP. 100% compatibility with JavaScript. Feedback please!

865 views
Skip to first unread message

Fredrik O

unread,
Oct 31, 2012, 6:37:32 PM10/31/12
to nod...@googlegroups.com
Hi everyone,

I have just wrote a simple lightweight OOP helper and want your thoughts about it, the implementation "Class" is only 15 lines of code, but I have included some tests, to show how it works. Any feedback is welcome. I am no JavaScript expert, but if I have not done anything wrong should always the generated class be 100% compatible with normal JavaScript prototype inheritance and indeed be very fast. It allows a user write somewhat more simple code.

See gist:  https://gist.github.com/3990372

What are your thoughts? Both negative and positive. And please, one comment is better than no one, so please comment if you read through the gist.

Thanks in advance!

Isaac Schlueter

unread,
Nov 1, 2012, 1:03:22 AM11/1/12
to nodejs
I would say you don't need this.

Just create a function with a capitalized first letter. That's your
class. Instantiate with `new`. Assign stuff to the prototype. Use
`util.inherits` (or the `inherits` module if you prefer) to do
inheritance, if you need to.

It's much better to write idiomatic JavaScript rather than twist
JavaScript to look like some other language. Yes, of course you *can*
do it, and you might learn something from it, but it's not actually a
good idea to use such things in real life. I'd suggest writing a few
more OOP helper wrapper doohickeys. In fact, continue writing them
until you see through the matrix of OOP to the true nature of
prototypes, and deeply grok that it's all just the same thing, so you
may as well use the one that's the most optimized by the VM, and the
most readily understandable to other users of the language.

That is, if you seek enlightenment. If you just wanna get something
done, use plain old boring JavaScript style OOP.
> --
> Job Board: http://jobs.nodejs.org/
> Posting guidelines:
> https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
> You received this message because you are subscribed to the Google
> Groups "nodejs" group.
> To post to this group, send email to nod...@googlegroups.com
> To unsubscribe from this group, send email to
> nodejs+un...@googlegroups.com
> For more options, visit this group at
> http://groups.google.com/group/nodejs?hl=en?hl=en

Mark Hahn

unread,
Nov 1, 2012, 1:05:26 AM11/1/12
to nod...@googlegroups.com
Or, just use coffeescript.  It offers great class support with `super`, etc, while using standard prototypes.

Isaac Schlueter

unread,
Nov 1, 2012, 1:25:27 AM11/1/12
to nod...@googlegroups.com
Trololololol ;p
To post to this group, send email to nodejs@g

Karl

unread,
Nov 1, 2012, 3:19:08 AM11/1/12
to nod...@googlegroups.com, i...@izs.me
And is that a metric or an imperial doohickey? If it's imperial it will not wrap well everywhere, better to write a thingamabob...
Trololololol ;p

> For more options, visit this group at
> http://groups.google.com/group/nodejs?hl=en?hl=en

--
Job Board: http://jobs.nodejs.org/
Posting guidelines: https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
You received this message because you are subscribed to the Google
Groups "nodejs" group.
To post to this group, send email to nod...@googlegroups.com
To unsubscribe from this group, send email to

For more options, visit this group at
http://groups.google.com/group/nodejs?hl=en?hl=en

Alexey Petrushin

unread,
Nov 1, 2012, 10:02:48 AM11/1/12
to nod...@googlegroups.com
Take a look at functional mixins, it's native to JS, requires zero-framework and looks much simpler and powerful than prototype - based.

Alexey Petrushin

unread,
Nov 1, 2012, 10:03:49 AM11/1/12
to nod...@googlegroups.com
Actually, after discovering functional mixins I stopped use classes in CoffeeScript.

Fredrik O

unread,
Nov 1, 2012, 5:10:59 PM11/1/12
to nod...@googlegroups.com, i...@izs.me
Thanks for answer, everyone :-)

Isaacs:

This is exactly what I am doing today, but I want to stop repeating myself, e.g "implement" the DRY principle, but stay 100% compatible with pure JavaScript prototype inheritance. So instead of manually create a function, assign a appropriate prototype to it and call "inherits" if I need to do some inheritance, do it in a automatic function which return a function which have exactly been initialized using this steps. Without it would I need to do all those things manually, no matter how. What is wrong with it?

Mark:

Thanks, but no thanks. I like the syntax of JavaScript more than CoffeScript, and just adding another language would increase the complexity of my software.

Alexey:

I have some read some about it, in others programming languages, but have forget about it in JavaScript. Definitely something I should look more into. Thanks for the tip :-)

tjholowaychuk

unread,
Nov 2, 2012, 12:08:48 AM11/2/12
to nodejs
I'm with isaac, personally I actually prefer re-declaring the
"Foo.prototype.<whatever> =" each method it re-establishes context.
Lots
of coffeescript is bad this way since you get half-way down the file,
you see some indented code and you have no clue what it's part of.
Same
goes for JavaScript using object-literals. This doesn't mean it has to
be ugly, just dont write ugly code but I strongly agree there's no
reason to
use these classical OO thingies

On Nov 1, 4:44 pm, Brian Link <cpsubr...@gmail.com> wrote:
> I like the look of those functional mix-ins.  Thanks for the link.

Wil Moore

unread,
Nov 2, 2012, 4:07:47 AM11/2/12
to nod...@googlegroups.com
I agree with Isaac,

Build classical function helpers as a learning experience, which which will show you that you don't need them.

Read and write a lot of idiomatic JavaScript and you'll quickly get over (and actually start to like) the syntax of "Constructor.prototype.*". I personally fought this for much longer than necessary. Once you get over it, hundred-line object literals (including the popular "module" pattern) will start to look extremely obtuse and superfluous.

Either way, JavaScript is really fun so go write cool things and enjoy it :)

Fredrik O

unread,
Nov 2, 2012, 11:46:50 AM11/2/12
to nod...@googlegroups.com
Thanks for answer, everyone, it is pleasant :-)

To just clear my point. I understand why raw JavaScript inheritance often is preferred, no need to know what "Class" does for example. Simply speaking can every single JavaScript programmer see what is going on. But now to my point.

Say I am writing many small modules. Those modules should only export some function who gives some type of functionality. The user of those modules only care about the functionality and how it behaves, not how it is actually implemented. Say now it takes somewhat shorter time when I use a helper function than it would without it, why should I not use then?

The "dependency" is included in the source, so every developer can fast and easily check it up. The generated function will have the same performance as the handwritten function probably and it will increase the readability of the source code somewhat. The function helper itself does not use any advanced JavaScript, all serious developers should understand it and no fancy stuff is added. So why is it not preferred to use a helper function in those situations? I cannot really get it when those advantages is applied.

greelgorke

unread,
Nov 2, 2012, 12:16:48 PM11/2/12
to nod...@googlegroups.com
1. do not use Class word :) 
2. it's ok to use helpers, DRY is key
3. your helper doesn't look very helpful for me
3.1  usage of your helper doesn't seem significant shorter than the pure way to write this things down, looks even more verbose to me, without serving readability (TJ's point)
3.2  everywhere Hardcoded reference to the "super"-Contsructor function -> changing the inheritance chain is more complicated at development time, even harder or impossible at runtime.  
4. it's not lightweight OOP but lightweight inheritance. OO is more than inheritance (in fact it doesn't even need inheritance)

my opinion from the first sight

greets

Fredrik O

unread,
Nov 2, 2012, 1:33:55 PM11/2/12
to nod...@googlegroups.com
Thanks for answer, greelgorke.

1. It is just a name of a variable.
2. I agree.
3. It only does what every developer must type down anyway to implement "classes" in JavaScript.
3.1 It don´t need to be significant shorter, but it is indeed shorter and more readable if you ask me. The purpose was never to do any fancy stuff like many others "Class" helpers, it was never the idea, but to automate those things you must do anyway. The returned object should always be 100% compatible with raw JavaScript "classes".
3.2 Please show a minimal example or give a link which will describe it more.
4. Wrong, OOP is about classes/objects and this is exactly what the helper function is about, by creating a minimal "class". A "class object" in the OOP world is anyway just a bunch of methods and a set of features, which I prefer to see separate.

Alexey Petrushin

unread,
Nov 2, 2012, 5:45:04 PM11/2/12
to nod...@googlegroups.com
> OO is more than inheritance (in fact it doesn't even need inheritance)
Depends on what do You mean by 'inheritance' - important part of OO is ability to easily create new objects by modifying and extending existing.

If You mean by inheritance - classical OOP class inheritance - then Yes it's not necessary, You can do the same with prototypes or metaprogramming or some other.

But OO needs inheritance in terms of - easy way to create new objects by modifying and extending existing - there should be a way to do it.

Dominick Pham

unread,
Nov 3, 2012, 9:42:58 AM11/3/12
to nod...@googlegroups.com
I think greelgorke's comment about not using Class as a variable is completely valid. 'class' is a reserved keyword, 'Class' probably won't ever be, but it's too close to a reserved keyword. In fact, I had to double check to make sure I wasn't crazy because I thought Class might have been reserved as well. I'm not a typist, I make mistakes when trying to type too fast, especially the kind where I miss the shift key. You should be kind to people like me.

Fredrik O

unread,
Nov 3, 2012, 10:35:01 AM11/3/12
to nod...@googlegroups.com
Thanks for answer, Dominick.

I know the word "class" is a reserved word. I only used it in the gist to make it more clear what it does. But the JavaScript library "joose" use it and I have never read anything negative about it. But in the end, it is just a name and the user is free to name it whatever she/he wants.

I only want to question way it is so wrong to use a helper function to return a function which we otherwise must explicitly create. We could to example in the gist remove the options.baseClass and put it in the method object and even rename it, if it feels more comfortable:

var Derived = lib({
  __inherits: Base, //inherits from Base
  constructor: function() {
    // constructor logic goes here
  },
  someMethod: function() {
    // someMethod logic goes here
  }
});

In which way I am not kind?

greelgorke

unread,
Nov 5, 2012, 4:01:58 AM11/5/12
to nod...@googlegroups.com
1. Yes, it is, but this word is overburden with a bunch of semantics and introduces the classical OO mindset immediately. But, it's your helper, name it like you wish and deal the with the consequences :)
3. I guess "helpful" is a matter of flavor and familiarity. i don't see the need to type down "classes" in js, may be thats the point.
3.1 a helper in a sense of DRY have to reduce amount of code. now instead of typing down the prototype, constructor etc, you have to pass objects, that's just anouther side of the same verbosity and it changes the semantics here a bit ("i use classical mindset now"). 
3.2 your gist: to change the prototype of the Derived2 class you have to change lines 
47: call to "base" constructor
51: call to getText from "base" proto, simulating super.getText
57: Change property baseClass

to change prototype at runtime you have to do even more, like replacing the getText property with a new function with the call to the new prototype. etc.

4. This is really a topic with potential to produce a next world war. there are so many definitions of OO and most of them are near by a dogma. OO is about Objects, objects encapsulate and hide internal data/state and offer public API to manipulate this data. Allan Key said in 2003:
 "OOP to me means only messaging, local retention and protection and hiding of state-process, and extreme LateBinding of all things."
No word of classes anymore. Classes are state of the art to define Types in OO, but its not the only way to do that. Inheritance is a preferred way to share and reuse Code in OO, but it's not the only way, "Favor Composition over Inheritance" is one of OO-Design Principles, because it's introduces looser coupling than the coupling offered by classical inheritance.
@Alexey: it's an easy way, becaue in most OO languages classical Inheritance is supported by the runtime. it offers all the clutter for dynamic lookup of methods/functions. But you could handle it also perfectly easy by mixing, borrowing, decorating/wrapping, curring etc. all it misses is the runtime support for such constructs. fortunately there are libs which can help.
In fact, if you really think about it, classical inheritance is nothing more than composition with tight coupling and automatic delegate resolution. JS prototypal inheritance allows loose coupling, and thats it what it make so powerful.

Greet :)

Fredrik O

unread,
Nov 5, 2012, 2:07:30 PM11/5/12
to nod...@googlegroups.com
Den måndagen den 5:e november 2012 kl. 10:01:58 UTC+1 skrev greelgorke:
3. I guess "helpful" is a matter of flavor and familiarity. i don't see the need to type down "classes" in js, may be thats the point.
3.1 a helper in a sense of DRY have to reduce amount of code. now instead of typing down the prototype, constructor etc, you have to pass objects, that's just anouther side of the same verbosity and it changes the semantics here a bit ("i use classical mindset now"). 
 
It reduces the amount of code you must type down:

var Name = helper({
  method1: function() {
  },
  method2: function() {
  },
  //..
});

vs

function Name() {
}
Name.prototype.method1 = function() {
};
Name.prototype.method2 = function() {
};
//...
Without the helper, you must repetitive times write: "Name.prototype". You can of course assign it in the function using this, but it is bad practice and has poor performance. And as soon you start to use any helper variable and function, do you use code you argue against.

3.2 your gist: to change the prototype of the Derived2 class you have to change lines 
47: call to "base" constructor
51: call to getText from "base" proto, simulating super.getText
57: Change property baseClass

to change prototype at runtime you have to do even more, like replacing the getText property with a new function with the call to the new prototype. etc.

And in which way can you skip this in normal prototype inheritance?

4. This is really a topic with potential to produce a next world war. there are so many definitions of OO and most of them are near by a dogma. OO is about Objects, objects encapsulate and hide internal data/state and offer public API to manipulate this data. Allan Key said in 2003:
 "OOP to me means only messaging, local retention and protection and hiding of state-process, and extreme LateBinding of all things."
No word of classes anymore. Classes are state of the art to define Types in OO, but its not the only way to do that. Inheritance is a preferred way to share and reuse Code in OO, but it's not the only way, "Favor Composition over Inheritance" is one of OO-Design Principles, because it's introduces looser coupling than the coupling offered by classical inheritance.

I am not a big fan of inheritance nor OO, but sure can it be great, same as multiple inheritance.

Jake Verbaten

unread,
Nov 5, 2012, 11:02:16 PM11/5/12
to nod...@googlegroups.com
function Name() {}

extend(Name.prototype, {
    ...
})

Tada. No more typing.


--
Job Board: http://jobs.nodejs.org/
Posting guidelines: https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
You received this message because you are subscribed to the Google
Groups "nodejs" group.
To post to this group, send email to nod...@googlegroups.com
To unsubscribe from this group, send email to

tjholowaychuk

unread,
Nov 5, 2012, 11:22:51 PM11/5/12
to nodejs
"without the helper, you must repetitive times write:
"Name.prototype""

still looks better, and the additional context is worth it IMO, plus
editors are good
at dealing with repetitive tasks, at least half the code I "write" is
not typed, I think the
same goes lots of devs
> >>  "*OOP to me means only messaging, local retention and protection and
> >> hiding of state-process, and extreme LateBinding<http://c2.com/cgi/wiki?LateBinding> of
> >> all things.*"

greelgorke

unread,
Nov 6, 2012, 4:06:56 AM11/6/12
to nod...@googlegroups.com
"And in which way can you skip this in normal prototype inheritance?"

using this.constructor.prototype.getText in the instance methods (also the non-standard shorthand this.__proto__ in code, that can be vendor-specific). in this case you can just assign another object as prototype and the code works, even at runtime. Of cause you could do this in your gist too, but you didn't. and TJ is right. Editors are good at the job to reduce typing and insert code patterns without changing the semantics. :) your tool, the helper, change it, not in it's implementation, but in it's usage, thats the main point. It hides the nature. JS knows and uses different extension patterns and your tool introduces (at usage point) the wrong semantic. as i said, inheritance is not the only way to reuse code and its valid even more for JS, where mixins and method borrowing are common technics. so as user i see your Class helper and do not know at this point, how it handles code re-usage. thats it.   


Am Montag, 5. November 2012 20:07:30 UTC+1 schrieb Fredrik O:
Den måndagen den 5:e november 2012 kl. 10:01:58 UTC+1 skrev greelgorke:
3. I guess "helpful" is a matter of flavor and familiarity. i don't see the need to type down "classes" in js, may be thats the point.
3.1 a helper in a sense of DRY have to reduce amount of code. now instead of typing down the prototype, constructor etc, you have to pass objects, that's just anouther side of the same verbosity and it changes the semantics here a bit ("i use classical mindset now"). 
 
It reduces the amount of code you must type down:

var Name = helper({
  method1: function() {
  },
  method2: function() {
  },
  //..
});

vs

function Name() {
}
Name.prototype.method1 = function() {
};
Name.prototype.method2 = function() {
};
//...
Without the helper, you must repetitive times write: "Name.prototype". You can of course assign it in the function using this, but it is bad practice and has poor performance. And as soon you start to use any helper variable and function, do you use code you argue against.

3.2 your gist: to change the prototype of the Derived2 class you have to change lines 
47: call to "base" constructor
51: call to getText from "base" proto, simulating super.getText
57: Change property baseClass

to change prototype at runtime you have to do even more, like replacing the getText property with a new function with the call to the new prototype. etc.



Alexey Petrushin

unread,
Nov 6, 2012, 4:28:29 AM11/6/12
to nod...@googlegroups.com
> And in which way can you skip this in normal prototype inheritance?
Not sure what do You mean, with functional mixins You can skip long prototype chains, there are always only one prototype in the chain. Methods assembled with applying set of function/mixins to it.

  // Declaring mixins.
  Persistence = fn(klass){
    // Sort-of class-level / singleton method.
    klass.findByName = fn(){}

    // Object - level method.
    klass.prototype.save = fn(){}
  }

  // Model
  Model = fn(){}

  // Injecting mixins.
  Persistence(Model)
  Validations(Model)

So, there's no need for long prototype chains.

It actually more advanced than prototypical because allows multiple inheritance and inheriting both class-level and obj-level methods.

Alexey Petrushin

unread,
Nov 6, 2012, 4:30:55 AM11/6/12
to nod...@googlegroups.com
Forgot about superclassing, here it is

  // Declaring mixins.
  Persistence = fn(klass){
    proto = klass.prototype
    
    proto.saveWithoutFeatureX = proto.save
    proto.save = fn(){}

Fredrik O

unread,
Nov 6, 2012, 1:32:08 PM11/6/12
to nod...@googlegroups.com
Thanks for answer, everyone. It is decent of you to take time to answer me.

Raynos:

First of was you not allowed to use helpers, but because you did will i show you a shorter alternative:

var Name = myHelper({
  //...
});

Tada. No more typing and it does exactly the same thing as your example.


tjholowaychuk:

I know editors can remove must of those typing, but as soon as your brain sees it, will it
process it and therefore take energy. It is the inconvenient truth of all humans. The advertising industry uses it
all the time. Because of this, even if you a perfect editor those will fix everything for you will it always be preferable to
have less code, as long as the code does not add any complexity, as it does not if you ask me.

greelgorke:

Same answer applies to you as tjholowaychuk, so you can read what I wrote to her/him as well. Your proposal  "this.constructor.prototype.getText" does not work by the way,  so it should be graceful if you can show a minimal code example. And if it exist would it be OK to use it in the helper method as well, because it should be 100% compatible with pure JavaScript inheritance.

Alexey Petrushin:

You are using mixins, nothing wrong with it, sometimes is it preferred to actually inherit from another object/function to gain the "is-a" relation. With mixins can you only gain the relation "has-a". It is not the same thing as the relation "is-a". The "instanceof" operator will not work only because you add some methods to a prototype, as it must if it is a "is-a" relation. You can however emulate it pretty good do I believe with correct instanceof behaviour.


To all:

The largest disadvantages the helper class has it is uses the arguments parameter to forward all calls. It will prevent huge optimizations if V8 is not smart enough.

greelgorke

unread,
Nov 6, 2012, 4:35:20 PM11/6/12
to nod...@googlegroups.com
@Point of reading: well, you might wander, but i developed a superability. i's named textscanning and is applyable to common patterns. advertisement industry try to break patterns to get you aware of the ad. thats the difference. if i see a prototypal based pattern, i just scan over it and look over the Constructor.prototype sentence as long it's always the same. BUT at the end its more a matter of taste than anything else.

@Example: I was too fast with my saying, i admit that. take a look at this:

function Base(){}
Base.prototype.t = function(){return 'BASE'}

function Sub(){}
Sub.prototype = new Base()

s = new Sub()
s.t() //'BASE'

Sub.prototype.t = function(){return 'SUB'}
s.t() //'SUB'
Sub.prototype.t = function(){return 'SUB'+ Sub.prototype.constructor.prototype.t()}
s.t() //'SUBBASE'

function Base2(){}
Base2.prototype.t = function(){return 'BASE2'}
Sub.prototype = new Base2()
s.t() // 'SUBBASE2'


at the end, both variants has their limitations. limitation in this example is the long property chain lookup to get the implementation of the prototype. in v8 you can use this.__proto__ instead of Sub.prototype.constructor.prototype, but __proto__ is non-standard. another disadvantage of this approach is, that the instances created before reassignment of Sub.prototype still link to old prototype-object. so if we continue the above example:

Sub.prototype.t = function(){return 'SUBSUB'}
s.t() //still returns SUBBASE2 not SUBSUB

for me, personaly, this is another issue thad drives me away from inheritance as code re-usage strategy. To many indirections and pitfalls. code sharing via simple prototype is ok, since it's prefered by v8 for optimisations. but i wouldn't reuse/extend objects with it if i don't have to.

@is-a/has-a: it's the point for inheritance. it's is rarely really  needed to establish is-a relation. It's about Identity or about protection of a library as a replacement for interface types? both are not really safe viable with instanceof, because constructor property is public and assignable. If i have to establish is-a relation, i'd rather do this via simple property than prototypes. in fact usage of instanceof is considered as smell and should be avoided anyway.

greet

José F. Romaniello

unread,
Nov 6, 2012, 9:32:04 PM11/6/12
to nod...@googlegroups.com
I really like this functional mixins thing, another good read is this one

http://killdream.github.com/blog/2011/10/understanding-javascript-oop/

Alexey Petrushin

unread,
Nov 7, 2012, 8:14:07 AM11/7/12
to nod...@googlegroups.com
> If i have to establish is-a relation, i'd rather do this via simple property than prototypes.

Exactly, I keept the sample small and ignore that part, if You need it You can use this

  Model = function(){}
  
  Validatable = function(klass){
    // do all needed extensions ...
    
    klass.prototype.isValidatable = true    
  }
  
  Validatable(Model)
  
  model = new Model()
  if(model.isValidatable) ...

tjholowaychuk

unread,
Nov 7, 2012, 11:53:14 PM11/7/12
to nodejs
Fredrick: less code does not make the code easier to digest, not even
close, the vast majority of coffeescript is much smaller, but
incredibly difficult to disambiguate in your head. Same with re-
declaring prototypes, sure it's "noise" but it establishes context.
Much like c++'s magical method invocation is ambiguous with function
calls, that's just garbage IMO, I'll never enjoy languages that
promote that sort of thing

Fredrik O

unread,
Nov 8, 2012, 10:58:09 AM11/8/12
to nod...@googlegroups.com
Most of you misses the point, it is sadly. Why it is preferred to have shorter code (as long it does not add any complexity) is it because it will make it easier to understand what is happening. That is the largest difference between a low level programming language and a high level programming language. It is the same thing when anyone type 1+1. It is indeed an abstraction and how it is implemented underneath can we just ignore.

In my opinion it is indeed better to group methods close to each other. My helper does not add any direct complexity and no "context" is lost, as long we know what we helper does as we do. However it has some advantages:

- It forces the user to write code which can easily be highly optimized by the JavaScript engine. All class methods will be defined in the prototype and all variables be bound to the object context. No need to be a good Java Script programmer.

- It can take multiple other compile options, so we can example add cache options, so the helper automatically set up a cache for some methods, specially deterministic methods. Multiple inheritance can probably also be properly implemented, so the instanceof operator will work as it can be expected, which in that case would be better to use than most mixins.

You most remember that if you create a mixin and when assign 10 different prototypes a set of methods (using a mixin) will the JavaScript engine have very hard to optimize it. What you do is actually indeed multiple inheritance, but you are not telling the JavaScript engine about it. If you would, would it probably give better performance, both in speed and memory consumption.

You does also a terrible mistake, even if an object has a set of methods, does it not mean it implements those methods in that way you may believe. The only properly way to actually check this is to use the instanceof operator. It would be most safe and probably the fastest way to check this.

tjholowaychuk:

I assume when you taking about C++ ambiguous invocation you mean operator overloading? A line like: "a = b + c" may invoke several functions. In that case can I tell you it is a huge benefit to the language and is there to make it easier to human to read, as long it is properly overloaded.

tjholowaychuk

unread,
Nov 8, 2012, 11:16:13 PM11/8/12
to nodejs
No I mean how "foo()" within a class method may be another method
call, global function etc, extremely lame "feature"

Fredrik O

unread,
Nov 9, 2012, 8:11:21 AM11/9/12
to nod...@googlegroups.com
Well, it can very easily be fixed. All good programmers would type "this->foo()" if any ambiguously may exist. And no, I disagree, it is not an "extreme" lame feature, but of course can it cause some problems if the programmer is not writing good readable code. It has some benefits however.

greelgorke

unread,
Nov 9, 2012, 8:21:51 AM11/9/12
to nod...@googlegroups.com
Just to, short, points:
1. you can easily trick the instanceOf operator, because the constructor Property is not write-protected by default.
2. "No need to be a good Java Script programmer." this sentence is just wrong. you should know your tools, in any environment. Thats my opinion. Disclaimer: this does not mean that i'm against helpers :)

Fredrik O

unread,
Nov 9, 2012, 8:44:35 AM11/9/12
to nod...@googlegroups.com
1. You can do many tricks as a programmer in any programming language, write ugly code, use anti patterns and so on, but that doesn´t mean you should.

2. When I wrote "good" I mean good as an expert. In that context would I say it is correct. You should of course know the programming language you use, but you should not need to be an expert at it. Besides, some programming language can it be very hard to be an expert in, even if the definition of "expert" is subjective.

greelgorke

unread,
Nov 9, 2012, 3:12:48 PM11/9/12
to nod...@googlegroups.com
ok, i see it's a fruitless, because very opinionated, discussion. :) use your helper, if you wish, i would use mine, if i need some. Thats ok. i'm fine with it. most importante thing is that we all happy with our tools. thats it.

Bruno Jouhier

unread,
Nov 9, 2012, 5:05:47 PM11/9/12
to nod...@googlegroups.com
Hi Frederik,

I wrote a helper very similar to yours (with a little plus: a concise syntax for property getters and setters) early in our project.

I just did a grep and we now have more than 250 classes in more than 200 modules defined with this helper. The helper keeps our code lean, consistent, well organized and pleasant to read. And, unlike some of the fancier helpers, it does not impact performance. Looking back, this is a total winner.

If this can make you feel better....

Bruno

Fredrik O

unread,
Nov 12, 2012, 7:47:26 AM11/12/12
to nod...@googlegroups.com
Hi Bruno,

It was nice to hear, thanks for sharing that information.

greelgorke:

I seek enlightenment and understanding in general. I wanted to get people thoughts and why they have those thoughts, by using as much as possible real arguments/fact, even if it may be hard within a subject like this. Thanks for your contribution (and everybody else for that sake) to this thread anyway :-)

greelgorke

unread,
Nov 12, 2012, 9:01:58 AM11/12/12
to nod...@googlegroups.com
@Fredrik: enlightenment and understanding are my targets too. That's why i love to talk about such topics as well. And my position, when it comes to a daily job, is: 

i would use your helper if i would contribute to your projects, and hell, yes i would contribute to your projects, if i had time and interest on the topics there. but i also would ask you, why do you use such a helper and try to trigger your thinking about it as well :). 

the worst thing is not that people use class-emulating helpers and libs, the worst thing is when they do it to avoid the confrontation with the language and it's internals. ignorance is the enemy, not tools. you said, one has not to be an expert, but a knowledge about fundamental concepts of the language is crucial. But many some developers just see "Class" and shutdown exploration mode in their brains, asume a paradigm, that isn't there, and wonder then,  why JS is so lame. 

Fredrik O

unread,
Nov 12, 2012, 10:57:53 AM11/12/12
to nod...@googlegroups.com
I cannot talk about others, every human has responsibility over their own knowledge and understanding. But I can talk for myself and I don´t stop thinking only because someone use the class word. I trying to see features and behaviour, and this behaviour is specially bound to the word "class" and "OOP". I choice to use the helper because:

- It makes the code more simple to read, if you ask me.
- It will generate a optimized class function which will be very fast and have low memory usage.
- It can implement optional options which allows cache long deterministic methods calls.
- It can implement helpers, like parent "class" with a little cost (compiler option)
- Better encapsulation
- If you speed up the "Class" function generated, will you speed up every instance of it.
- Automatic generate methods, like default constructors, setters, getters, and mix-in behaviour.
- Add "destructor" and therefore allow some light RAII, which is in my opinion the right solution to solve resource leaks.
- It is 100% compatible with every hard coded class function, I can use it together with any existing "class" function.

By using your arguments would it be equal to say it is stupid to abstract away things to be able to look at something on a more higher level. Functions was made for this task together with code reuse. You would´t normally write the same code twice but create a function for it, but when the same thing for "class generation" is it suddenly a "confrontation with the language", even I use the most powerful feature of the language? I simply don´t agree.

Alexey Petrushin

unread,
Dec 10, 2012, 11:05:56 AM12/10/12
to nod...@googlegroups.com
I wrote short article about Functional Mixins with simple example, maybe it will be useful http://petrush.in/blog/2012/functional-mixins

Azer Koçulu

unread,
Dec 10, 2012, 7:41:50 PM12/10/12
to nod...@googlegroups.com
I re-wrote your example using a new library that I'm working on; 


Here is another example: https://gist.github.com/4136102

And this is the library: http://github.com/azer/ak47


--

Jake Verbaten

unread,
Dec 10, 2012, 11:53:35 PM12/10/12
to nod...@googlegroups.com
Why is this so hard?

Why do we need unnecessary OOP abstractions.

Use functions, it's really really simple. https://gist.github.com/4255961

```js
function Base(text) {
    return function () {
        return text
    }
}

function Derived(source, prefix) {
    var text = Base(source)

    return function () {
        return prefix + text() + prefix
    }
}

function Derived2(source, prefix, color) {
    var text = Derived(source, prefix)

    return function () {
        return color + text()
    }
}

var d = Derived('foo', '!'),
    d2 = Derived2('bar', '!', 'red'),

    assert = require('assert');

assert.equal( d(), '!foo!' );
assert.equal( d2(), 'red!bar!' );
```

Luke Arduini

unread,
Dec 13, 2012, 1:24:31 AM12/13/12
to nod...@googlegroups.com
I have yet to hear a particularly convincing argument for this type of OOP in javascript. As Raynos and Isaac explained, the idiomatic js style way without some additional special wrapper or helper is trivial to do.

"I like it more" is a fine reason to do it yourself. I think it's a waste of time but it's not my time.

Please for the love of science however don't encourage js newcomers to write their code like this.

Reply all
Reply to author
Forward
0 new messages