473,626 Members | 3,392 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

(Yet another) simple JS OO framework (by a python programmer)

aum
Hi,

I'm a Python programmer, just starting to get into javascript. On reading
some of the js guides, and not liking any of the OO usage patterns I saw,
I've cooked up something which python folks might find to taste.

Here's the code - first the 'engine', then some code demonstrating the
usage patterns.

For me (and maybe for some of you), it promotes readability and some
pattern similarity for classical OO languages.

Cheers
aum
*** start code ***

// this is the 'engine' of it all - usage patterns follow

Object.prototyp e.subclass = function(props) {

// extract 'init' function from property list, or
// use a null default function
if (props.hasOwnPr operty('init')) {
constructor = props['init']
}
else {
constructor = function() {}
}

// set up inheritance
constructor.pro totype = new this();

// populate prototype object with all properties except init
for (key in props) {
if (key != 'init' && key != 'subclass') {
//alert("Inheriti ng property '" + key + "'");
constructor.pro totype[key] = props[key];
}
}

// done
return constructor;
}

// USAGE PATTERNS

// Create 'employee' class
employee = Object.subclass ({

init: function(name) {
this.name = name;
},

getname: function() {
return this.name;
},

toString: function() {
return "[employee: "+this.name +"]";
}
})

// Create engineer class
engineer = employee.subcla ss({

init: function(name, project) {

// invoke parent initialiser
employee.apply( this, [name]);

// do local initialisations
this.project = project;
},

getproject: function() {
return this.project;
},

toString: function() {
return "[engineer: "+this.name +"(" + this.project + ")]";
}

})

// Create 'engineer's assistant' class
assistant = engineer.subcla ss({

init: function(name, boss) {

// invoke parent initialiser
engineer.apply( this, [name, boss.project]);

this.boss = boss
},

getboss: function() {
return this.boss;
},

toString: function() {
return "[assistant: "+this.name + " (reporting to "+this.boss +")]";
},
})

alert("Construc ting employee 'fred'...");
fred = new employee("Fred Dagg")
alert("Construc ting engineer 'mary'...");
mary = new engineer("Mary Smith", "Networks")

alert("Construc ting assistant 'jim'...");
jim = new assistant("Jim Jones", mary)

alert("fred.nam e='" + fred.name + "'");
alert("fred.get name() = '" + fred.getname() + "'");

alert("mary.pro ject='" + mary.project + "'");
alert("mary.get project() = '" + mary.getproject () + "'");

alert("mary.nam e='" + mary.name + "'");
alert("mary.get name() = '" + mary.getname() + "'");

alert("jim.name ='" + jim.name + "'");
alert("jim.boss ='" + jim.boss.name + "'");
Sep 17 '06 #1
13 2030
aum wrote:
I'm a Python programmer, just starting to get into javascript.
Which makes you the best person to be judging how javascript should be
used?
On reading some of the js guides, and not liking any of
the OO usage patterns I saw, I've cooked up something
which python folks might find to taste.
<snip>

One of the consequences of trying to make javascript resemble other
programming languages as those rewarded by the effort tend to start
applying the expectations and pre-conceptions of that other language to
javascript, only to be ultimately disappointed. There is a great deal to
be said for people adopting a javascript mindset when they wrote
javascript.
*** start code ***

// this is the 'engine' of it all - usage patterns follow

Object.prototyp e.subclass = function(props) {
<snip>
// set up inheritance
constructor.pro totype = new this();
It seems a little perverse to be crating a property of -
Object.prototyp e - that can only be called in a way where the - this -
reference is a reference to a function. This would feel better if the -
subclass - method was an extension of - Function.protot ype -. It would
work as well in that case, but that change would also have the advantage
of not modifying the - Object.prototyp e - by adding an enumerable
property. Such an adition to Object.prototyp e - has implications for all
uses of - for-in - loops on javascript objects, while enumerating the
properties of functions is uncommon so much less of a problem.
// populate prototype object with all properties except init
for (key in props) {
<snip>

Here - key - has not been declared as a local variable, so all
assignments to it act as assignments to a property of the global object
(effectively a global variable). This is a very bad practice. The
general programming axiom that no variable should be given more scope
than it absolutely needs is as true in javascript as it is in any other
language. And chaotic results will follow from any attempt to subclass
one object while subclassing another, as they will be sharing the -
key - variable. (That may be an improbable contingency but risk can be
eliminated entirely by decrying the variable locally)

Richard.
Sep 17 '06 #2
aum
On Sun, 17 Sep 2006 15:23:40 +0100, Richard Cornford wrote:

Firstly - thanks for your reply.
>I'm a Python programmer, just starting to get into javascript.
Which makes you the best person to be judging how javascript should be
used?
No way - it makes me someone who has gotten very comfortable with python,
who is feeling way out of his comfort zones with javascript, and is
wrestling with the issue of how to write code in javascript that is
similarly readable and understandable.

What I'm trying to do is render the common javascript idiom:

function Manager (name, dept) {
this.base = Employee;
this.base(name, dept);
this.reports = [];
}
Manager.prototy pe = new Employee;
Manager.prototy pe.addReport = function(employ ee) {
this.reports.pu sh(employee);
}

as something I'm (presently) finding more intuitive and readable, eg:

Manager = subclass(Employ ee, {

init: function(name, dept) {
Employee.apply( this, [name, dept])
},
addReport: function(employ ee) {
this.reports.pu sh(employee);
}
})
One of the consequences of trying to make javascript resemble other
programming languages as those rewarded by the effort tend to start
applying the expectations and pre-conceptions of that other language to
javascript, only to be ultimately disappointed.
I can understand and respect that.

I do accept that the web browser development organisations are not about
to work together to support client-side python scripting in any great
hurry, so I'm going to have to relax my cling on the python paradigm, and
figure out how to get my brain thinking javascript.
There is a great deal to
be said for people adopting a javascript mindset when they wrote
javascript.
Maybe you can recommend some websites and portals, beyond the core
language and dom guides etc, that help people from other language
backgrounds to appreciate 'javascript-flavoured reality'.
It seems a little perverse to be crating a property of -
Object.prototyp e - that can only be called in a way where the - this -
reference is a reference to a function.
I could just as easily implement 'subclass' as a global function accepting
as arguments the base class and a property mapping for the new class (see
below).
Here - key - has not been declared as a local variable, so all
assignments to it act as assignments to a property of the global object
(effectively a global variable).
Thanks for the correction - I was still thinking python, where variables
are local-by-default, not global-by-default. My bad.

Anyway, here's my amended implementation:

function subclass(base, props) {
var constructor, key;

// extract 'init' function from property list, or
// use a null default function
if (props.hasOwnPr operty('init')) {
constructor = props['init']
}
else {
constructor = function() {}
}

// set up inheritance
constructor.pro totype = new base();

// populate prototype object with all properties except init
for (key in props) {
if (key != 'init') {
constructor.pro totype[key] = props[key];
}
}

return constructor;
}

As a javascript neophyte, I do throw myself open to this group for
constructive suggestions and feedback.

Cheers
aum
Sep 17 '06 #3
aum
I've written up my subclassing scheme at:

http://www.freenet.org.nz/misc/jsoo.html

Cheers
aum
Sep 17 '06 #4
aum wrote:
Richard Cornford wrote:
<snip>
>>I'm a Python programmer, just starting to get into
javascript.
>Which makes you the best person to be judging how
javascript should be used?

No way - it makes me someone who has gotten very comfortable
with python, who is feeling way out of his comfort zones with
javascript, and is wrestling with the issue of how to write
code in javascript that is similarly readable and
understandable.

What I'm trying to do is render the common javascript idiom:

function Manager (name, dept) {
this.base = Employee;
this.base(name, dept);
this.reports = [];
}
Manager.prototy pe = new Employee;
Manager.prototy pe.addReport = function(employ ee) {
this.reports.pu sh(employee);
}

as something I'm (presently) finding more intuitive and
readable, eg:

Manager = subclass(Employ ee, {

init: function(name, dept) {
Employee.apply( this, [name, dept])
},
addReport: function(employ ee) {
this.reports.pu sh(employee);
}
})
And after years of javascript programming I find the former second
nature and the latter unfamiliar and obscure.

One question that has arisen when people have tried to dress javascript
up as some other language in the past is where do people who adopt these
systems go when they need help. Often they will come to
comp.lang.javas cript, where they find themselves presenting code that is
unfamiliar and obscure to the people who they want answers from. But if
the question is related to the internal details of javascript there is
little point going to the authors of these systems for help, as their
intention was to avoid becoming familiar with javascript from the
outset.

Javascript is flexible enough to be bent into all sorts of shapes. As
javascript it can be enjoyed for its flexibility. Once bent into a
python-like, or pear-like, or Java-like shape there may not be the same
flexibility left.

<snip>
>There is a great deal to be said for people adopting a
javascript mindset when they wrote javascript.

Maybe you can recommend some websites and portals, beyond
the core language and dom guides etc, that help people
from other language backgrounds to appreciate
'javascript-flavoured reality'.
What would be wrong with reading comp.lang.javas cript? You probably
cannot assume that everyone will know python but if you can explain the
concepts from python that interest you any parallels and possibilities
in javascript probably can be made clear.
>It seems a little perverse to be crating a property of -
Object.prototy pe - that can only be called in a way
where the - this - reference is a reference to a function.

I could just as easily implement 'subclass' as a global
function accepting as arguments the base class and a
property mapping for the new class (see below).
You could do that, but an extension of the - Function.protot ype - object
would be the more javascript-like way of achieving what you had done. It
would also keep another function object out of the global namespace.
>Here - key - has not been declared as a local variable,
so all assignments to it act as assignments to a property
of the global object (effectively a global variable).

Thanks for the correction - I was still thinking python, where
variables are local-by-default, not global-by-default. My bad.
Doesn't that rather make my point about having to adopt a javascript
mindset to write javascript?

Where I work there are people writing Java and people writing
javascript, and a few doing both. As Java and javascript are quite
similar in syntax/structure, when we wrote the javascript coding
standards document it was agreed to adopt a block layout/indentation
structure that was deliberately distinct from the one in the existing
Java coding standards document. That was a deliberate effort to make the
two languages as visually distinct as possible, and so encourage
programmers to think Java when writing Java and think javascript when
writing javascript. That and the fact that both Java and javascript may
appear together in JSP code and then telling one form the other at a
glance is useful (in a JSP they would be subject to the same
syntax-highlighting scheme).

<snip>
As a javascript neophyte, I do throw myself open to
this group for constructive suggestions and feedback.
Where 'constructive' advice may include abandoning an idea entirely
and/or starting again from scratch it may be perceived and
non-constructive. If you post here you will get what you will get.

Richard.
Sep 17 '06 #5

aum wrote:
Hi,

I'm a Python programmer, just starting to get into javascript. On reading
some of the js guides, and not liking any of the OO usage patterns I saw,
I've cooked up something which python folks might find to taste.

Here's the code - first the 'engine', then some code demonstrating the
usage patterns.

For me (and maybe for some of you), it promotes readability and some
pattern similarity for classical OO languages.

Cheers
aum
*** start code ***

// this is the 'engine' of it all - usage patterns follow

Object.prototyp e.subclass = function(props) {
When Sam Stephenson initially developed the Prototype library he added
to the prototype of Object and he caught utter hell for it, for a lot
of good reasons. He later relented. He now adds to the prototype of
Array and String and most of the other types, but not Object.

More here:

http://sam.conio.net/

Sep 18 '06 #6

Richard Cornford wrote:
One question that has arisen when people have tried to dress javascript
up as some other language in the past is where do people who adopt these
systems go when they need help. Often they will come to
comp.lang.javas cript, where they find themselves presenting code that is
unfamiliar and obscure to the people who they want answers from. But if
the question is related to the internal details of javascript there is
little point going to the authors of these systems for help, as their
intention was to avoid becoming familiar with javascript from the
outset.
In the end, it comes down to community, and how much support that
community can offer. If there sprang up a large, cohesive, helpful
community of people dedicated to making Javascript look like Python,
then those who wanted to do so could certainly get away with it. That
has already happened for the group that wants to make Javascript look
like Ruby. They've several large, very active forums where people can
go if they prefer to write Javascript that looks just like Ruby:

http://groups.google.com/group/rubyo...pinoffs?lnk=li

These folk use Prototype to give Javascript an each() method just like
Ruby, and to give Javascript associative arrays. For this crew, the
most exciting about Javascript is how much it can be made to look like
Ruby, as this article explains:

http://encytemedia.com/blog/articles...array-and-hash

There are at this point large subgroups using Javascript that have
their own forums for dealing with their particular issues.
comp.lang.javas cript seems to be overly focused on the web. During 2005
my biggest freelance gig involved automating catalog production for a
large jewelry company, using Javascript to script Adobe Photoshop and
Adobe InDesign. I relied on the Adobe forums when I had questions about
using Javascript in that space. Those questions would have seemed out
of place on comp.lang.javas cript. I was dealing with the same language
but a very different API. It's a different community.

Likewise, the community that wants Javascript to look like Ruby is
setting up its own forums, because they understand that their issues
are special and may not belong on a mainstream Javascript site.

Right now, the main failing with making Javascript look like Python, is
that there is no large community supporting it. Each programmer who
goes down this road needs to find their own way. This could, of course,
change.

Sep 18 '06 #7
Jake Barnes wrote:
Richard Cornford wrote:
>One question that has arisen when people have tried to dress
javascript up as some other language in the past is where do
people who adopt these systems go when they need help.
Often they will come to comp.lang.javas cript, where they find
themselves presenting code that is unfamiliar and obscure to
the people who they want answers from. But if the question
is related to the internal details of javascript there is little
point going to the authors of these systems for help, as their
intention was to avoid becoming familiar with javascript from
the outset.

In the end, it comes down to community, and how much support
that community can offer.
Probably it does, but how much support can a community offer when it is
defined by a desire to avoid using javascript as such?
If there sprang up a large, cohesive, helpful community of
people dedicated to making Javascript look like Python,
then those who wanted to do so could certainly get away with it.
Being able to "get away" with something does not make it a good idea.
Indeed in web development a great deal has been gotten away with that
would not have stood up to informed scrutiny.
That has already happened for the group that wants to make Javascript
look like Ruby. They've several large, very active forums where people
can go if they prefer to write Javascript that looks just like Ruby:

http://groups.google.com/group/rubyo...pinoffs?lnk=li

These folk use Prototype
When people who have a good understanding of javascript and browser
scripting (which is the application of the Prototype library) reject
the use of the Prototype library (for many reasons, including it
fundamental design flaws, inherent complexity and consequential
inefficiency) the implication is that the people who support the
prototype library are relatively ignorant of javascript. The result of
an isolated group operating in relative ignorance of javascript may
just be the propagation of a story (if maybe a logically consistent
story) about javascript in place of any actual knowledge of the
subject. It is like the HTML comment-like structures in script elements
thing; such ideas propagate well beyond their usefulness, along with
mystical justifications, when there is nobody around the challenge
them.
to give Javascript an each() method just like
Ruby, and to give Javascript associative arrays. For this crew, the
most exciting about Javascript is how much it can be made to look
like Ruby, as this article explains:
And if they wanted to they could implement a full Ruby
interpreter/compiler in javascript and be in a position to write 100%
ruby to script web pages. The goal of scripting a cline with Ruby would
be completely achieved.
http://encytemedia.com/blog/articles...array-and-hash
While a javascript centric approach to hashtables is to see when an
enumerable hashtable implementation is necessary and then include one.
The end result functionality is the same, but the efficiently is
considerably better and there are minimal knock-on effects on the rest
of the environment.
There are at this point large subgroups using Javascript that have
their own forums for dealing with their particular issues.
comp.lang.javas cript seems to be overly focused on the web.
Only because the majority of the applications of javascript are
client-side in web pages. There is no reason for not discussing
javascript's use in other environments, its just a matter of people
asking answerable questions.
During 2005 my biggest freelance gig involved automating catalog
production for a large jewelry company, using Javascript to script
Adobe Photoshop and Adobe InDesign. I relied on the Adobe
forums when I had questions about using Javascript in that space.
Those questions would have seemed out of place on
comp.lang.javas cript.
They may have seemed out of place, but they are not. The usefulness of
asking them depends on the question. There is certainly little value in
asking questions about the Adobe object models without referring
readers who are likely to be unfamiliar with those object models to the
pertinent documentation, but an ECMAScript implementation will still be
an ECMAScript implementation whatever object model it is scripting.
I was dealing with the same language
but a very different API. It's a different community.
Not necessarily. Javascript is designed to script differing object
models in differing environments.
Likewise, the community that wants Javascript to look like Ruby is
setting up its own forums, because they understand that their issues
are special and may not belong on a mainstream Javascript site.
They may understand their own issues (though it doesn't look like they
fully understand them to me) but they first created their own issues.
Right now, the main failing with making Javascript look like Python, is
that there is no large community supporting it.
Not that it is an inherently bad idea?
Each programmer who goes down this road needs to find their own way.
Especially when the advice they are given is not to start on that road
to begin with.
This could, of course, change.
There will never be a time when everyone wants to program javascript as
if it was python, or any other non-javascript language.

Richard.

Sep 19 '06 #8

Richard Cornford wrote:
Jake Barnes wrote:
In the end, it comes down to community, and how much support
that community can offer.

Probably it does, but how much support can a community offer when it is
defined by a desire to avoid using javascript as such?
If there sprang up a large, cohesive, helpful community of
people dedicated to making Javascript look like Python,
then those who wanted to do so could certainly get away with it.

Being able to "get away" with something does not make it a good idea.
Indeed in web development a great deal has been gotten away with that
would not have stood up to informed scrutiny.
That has already happened for the group that wants to make Javascript
look like Ruby. They've several large, very active forums where people
can go if they prefer to write Javascript that looks just like Ruby:

http://groups.google.com/group/rubyo...pinoffs?lnk=li

These folk use Prototype

When people who have a good understanding of javascript and browser
scripting (which is the application of the Prototype library) reject
the use of the Prototype library (for many reasons, including it
fundamental design flaws, inherent complexity and consequential
inefficiency) the implication is that the people who support the
prototype library are relatively ignorant of javascript. The result of
an isolated group operating in relative ignorance of javascript may
just be the propagation of a story (if maybe a logically consistent
story) about javascript in place of any actual knowledge of the
subject. It is like the HTML comment-like structures in script elements
thing; such ideas propagate well beyond their usefulness, along with
mystical justifications, when there is nobody around the challenge
them.
I agree with much of what you said, but I think the people behind
Prototype are aware of the potential negative effects of using
Prototype. "Inheritanc e madness" is an often used phrase, by people who
like Prototype and would like to see it improved.

http://encytemedia.com/blog/articles...itance-madness

To my mind, the most important criticism of Prototype is that it
doesn't play well with others. It breaks a lot of existing code out
there.

Sep 20 '06 #9
Jake Barnes wrote:
Richard Cornford wrote:
>Jake Barnes wrote:
<snip>
>>That has already happened for the group that wants to make
Javascript look like Ruby. ...
<snip>
http://groups.google.com/group/rubyo...pinoffs?lnk=li

These folk use Prototype

When people who have a good understanding of javascript and
browser scripting (which is the application of the Prototype library)
reject the use of the Prototype library (for many reasons, including
it fundamental design flaws, inherent complexity and
consequentia l inefficiency) the implication is that the people who
support the prototype library are relatively ignorant of javascript.
The result of an isolated group operating in relative ignorance of
javascript may just be the propagation of a story (if maybe a
logically consistent story) about javascript in place of any actual
knowledge of the subject. ...
<snip>
I agree with much of what you said, but I think the people behind
Prototype are aware of the potential negative effects of using
Prototype.
I don't believe that. The consequences of being aware would not be the
continued development of Prototype.
"Inheritanc e madness" is an often used phrase, by people who
like Prototype and would like to see it improved.

http://encytemedia.com/blog/articles...itance-madness

To my mind, the most important criticism of Prototype is that it
doesn't play well with others. It breaks a lot of existing code out
there.
Playing well with other scripts is a problem inherent in libraries, and
so ultimately avoidable. I would worry more about the ludicrous
complexity, the indirection, the inflexibility and the performance
overheads. Though the thing with that is that I know what the users of
Prototype are missing, while they only know what they want from what
they have.

Richard.

Sep 20 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

37
2556
by: Michele Simionato | last post by:
At work we are shopping for a Web framework, so I have been looking at the available options on the current market. In particular I have looked at Paste and Pylons and I have written my impressions here: http://www.phyast.pitt.edu/~micheles/python/yet-another-comparison-of-web-frameworks.html I do not speak too well of Pylons, so if you thing I am wrong feel free to correct me here ;)
0
8196
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8701
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8364
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8502
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6122
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5571
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4090
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4196
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2623
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.