471,353 Members | 1,553 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,353 software developers and data experts.

creating functions to work like library functions

And that is probably very unclear - so let me explain. Please forgive me
if I screw up the terminology (and let me know what the correct term
would be):

What I want to do is to create a library 'namespace' to encapsulate
certain functions that have something in common. I want it to work in
the way the Math() object works - by calling it directly, instead of
having to instantiate it as a variable (object?)

For example, with the Math object, I can just make a call to
Math.floor() directly - I don't have to go through the hoops of
delcaring something like:

var math = new Math();
So, lets say I have this:

<script type="text/javascript">
function MyLibrary() {

this.sayHi = function() {
alert('Hi!');
}

this.saySomething = function(something) {
alert(something);
}
}
</script>
In order to use 'sayHi', I have to instantiate this:

var library = new MyLibrary();
library.sayHi();
What I WANT to do is just say:

MyLibrary.sayHi();

-> So, my question is - is there any way to do this?

Links are also appreciated - I'd google it, but I don't even know what
to put in the search box - I'm pretty sure my terminology is way off.

Thanx
Apr 27 '06 #1
13 1449

Tony wrote:
And that is probably very unclear - so let me explain. Please forgive me
if I screw up the terminology (and let me know what the correct term
would be):

What I want to do is to create a library 'namespace' to encapsulate
certain functions that have something in common. I want it to work in
the way the Math() object works - by calling it directly, instead of
having to instantiate it as a variable (object?)

For example, with the Math object, I can just make a call to
Math.floor() directly - I don't have to go through the hoops of
delcaring something like:

var math = new Math();
So, lets say I have this:

<script type="text/javascript">
function MyLibrary() {

this.sayHi = function() {
alert('Hi!');
}

this.saySomething = function(something) {
alert(something);
}
}
</script>
In order to use 'sayHi', I have to instantiate this:

var library = new MyLibrary();
library.sayHi();
What I WANT to do is just say:

MyLibrary.sayHi();

-> So, my question is - is there any way to do this?

Links are also appreciated - I'd google it, but I don't even know what
to put in the search box - I'm pretty sure my terminology is way off.

Thanx


What you are describing is what is called a "static object". Meaning
that you don't have to create an instance of it to use its properties
and methods. Both Date and Math are examples of static objects.

Using your example, here is how you would do it...

function MyLibrary() { //Can leave empty or declare private members }

MyLibrary.staticvariablehere = value;
MyLibrary.staticmethod = function (params) { //body of method here };

Then from that point on you can use MyLibrary.staticvariablehere and
MyLibrary.staticmethod(params).

This is an overly simplified version but should work for you. The link
below briefly talks about it also...

http://www.pasz.com/articles/JSInheritance.html

Just keep in mind that variables and methods defined this way do not
have direct access to private members defined in the constructor. You
are adding to the template of the class, not instances. Either way,
this should do exactly what you need. Hope it works for you.

Apr 27 '06 #2
Tony wrote:
And that is probably very unclear - so let me explain. Please forgive me
if I screw up the terminology (and let me know what the correct term
would be):

What I want to do is to create a library 'namespace' to encapsulate
certain functions that have something in common. I want it to work in
the way the Math() object works - by calling it directly, instead of
having to instantiate it as a variable (object?)

For example, with the Math object, I can just make a call to
Math.floor() directly - I don't have to go through the hoops of
delcaring something like:

var math = new Math();
So, lets say I have this:

<script type="text/javascript">
function MyLibrary() {

this.sayHi = function() {
alert('Hi!');
}

this.saySomething = function(something) {
alert(something);
}
}
</script>
In order to use 'sayHi', I have to instantiate this:

var library = new MyLibrary();
library.sayHi();
What I WANT to do is just say:

MyLibrary.sayHi();

-> So, my question is - is there any way to do this?
Yes. In addition to the way suggested by Martyr2 you can use:
var MyLibrary = (function()
{
var privateVar = 'blah';

function privateMethod(){ /*...*/ }

// Public methods
return {
sayHi : function() {
alert('Hi');
},
saySomething : function(something) {
alert(something);
}
}
})();
// Call the public methods
MyLibrary.sayHi();
MyLibrary.saySomething('blah blah');
You can also have privileged methods so you can change the value of
privateVar, which would otherwise be inaccessible to functions outside
MyLibrary.

It is convention to use a capital letter for the names of constructors,
and also library names should be kept short since they prefix all your
method calls.

Another way is to create an object and add stuff to its prototype,
though if you aren't going to use it as a constructor then the
difference between adding to the prototype or directly to the object may
be of no interest.

Links are also appreciated - I'd google it, but I don't even know what
to put in the search box - I'm pretty sure my terminology is way off.


Try this:

<URL:http://javascript.crockford.com/private.html>
--
Rob
Apr 27 '06 #3
Martyr2 wrote:
Tony wrote: <stuff>
What you are describing is what is called a "static object". Meaning
that you don't have to create an instance of it to use its properties
and methods. Both Date and Math are examples of static objects.
Ah - thanx for the clarification.
Using your example, here is how you would do it...

function MyLibrary() { //Can leave empty or declare private members }

MyLibrary.staticvariablehere = value;
MyLibrary.staticmethod = function (params) { //body of method here };

Then from that point on you can use MyLibrary.staticvariablehere and
MyLibrary.staticmethod(params).
Hmm - I tried that but it didn't work. Maybe I did something wrong -
I'll give it another go.

This is an overly simplified version but should work for you. The link
below briefly talks about it also...

http://www.pasz.com/articles/JSInheritance.html


And thanks for the link - that will help quite a bit, I think.
Especially now that I know what to call what I'm looking for :)
Apr 27 '06 #4
Martyr2 wrote:
function MyLibrary() { //Can leave empty or declare private members }
MyLibrary.staticvariablehere = value;
MyLibrary.staticmethod = function (params) { //body of method here };


An alternative method, which I use in my libraries on javascripttoolbox.com
:

var Library = (function(){
var lib = {};
lib.func1 = function(x) { alert(x); }
lib.func2 = function(y) { lib.func1(y) }
return lib;
})();
Library.func2("test");

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Apr 27 '06 #5
Tony wrote:
Martyr2 wrote:
Using your example, here is how you would do it...

function MyLibrary() { //Can leave empty or declare private members }

MyLibrary.staticvariablehere = value;
MyLibrary.staticmethod = function (params) { //body of method here };
<...>
Hmm - I tried that but it didn't work. Maybe I did something wrong -
I'll give it another go.

Ah - I see what I was doing wrong. I did this:

function MyLibrary() {
MyLibrary.staticMethod = function() {}
}

instead of:

function MyLibrary() {}
MyLibrary.staticMethod = function() {}

---

I notice that defining a function withing MyLibrary using
this.functionName creates a function that is available to objects of the
class MyLibrary, but not to the class (static object) directly.
Apr 27 '06 #6
Tony said on 28/04/2006 8:06 AM AEST:

[...]
I notice that defining a function withing MyLibrary using
this.functionName creates a function that is available to objects of the
class MyLibrary, but not to the class (static object) directly.


The value of 'this' is established *when the function is executed*, not
when it is declared - read section 10.2 of the ECMA spec.

When you call a function directly that has been declared in the global
scope, its 'this' value is the global object. When you call the
function as a constructor using 'new', its 'this' value is the newly
created object.

If it's attached it to an DOM element event handler using a reference,
'this' will refer to the object it's attached to.

// Declare a function
function test(){ alert(this); }

// Call directly
test();

// Call as a constructor
var x = new test();

// Attach to a DOM object
var domObj = document.getElementById('someEl');
domObj.onclick = test;
Using Firefox, you'll see alerts with '[object Window]' and '[object
Object]', IE says '[object]' and '[object Object]'. Click on 'someEl'
(say it's a div) and in Firefox you'll see '[object HTMLDivElement]', IE
just says '[object]'.

The important thing to remember is that the value of 'this' is dependent
on how the function is called, not necessarily on where it is declared
or initialised (though of course that will affect how you can call it,
indirectly affecting the value of 'this' to some extent).

I have yet to find a good article on 'this', I've tried writing one but
I can't make it sensible. It requires a thorough understanding of
function declaration, instantiation and execution to be able to explain
it simply - maybe someone has a reference?
--
Rob
Group FAQ: <URL:http://www.jibbering.com/FAQ>
Apr 27 '06 #7
On 28/04/2006 00:22, RobG wrote:

[snip]
I have yet to find a good article on 'this',
Of the posts you've read in the archives, and perhaps other on the Web,
in what ways have you found them wanting? Do they provide too much
information? Too little? Do they assume too much background information?
Are they inaccessible (too much technical jargon)? Are there too few
examples?

Writing a good, reusable explanation requires feedback or an outstanding
author. Surely there's an article somewhere that, with some tweaking,
would be good enough to serve as a reference document.
I've tried writing one but I can't make it sensible.


You could always post it (or a link) here. You might get suggestions.

Though composition is hardly the focus of this group, I don't see the
harm in contributors who are comfortable with and adept at writing
(which eliminates me :-) helping others in that regard. There's little
point in having knowledge in a group like this if one lacks the ability
to convey it to others.

Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Apr 28 '06 #8
RobG wrote:
Tony said on 28/04/2006 8:06 AM AEST:

The value of 'this' is established *when the function is executed*, not
when it is declared - read section 10.2 of the ECMA spec.
I suppose I'll have to give in and actually read that. Specs give me a
headache :)
The important thing to remember is that the value of 'this' is dependent on how the function is called, not necessarily on where it is declared
or initialised (though of course that will affect how you can call it,
indirectly affecting the value of 'this' to some extent).
Good to know.
I have yet to find a good article on 'this', I've tried writing one but
I can't make it sensible. It requires a thorough understanding of
function declaration, instantiation and execution to be able to explain
it simply - maybe someone has a reference?


If you don't come across any, maybe we could work it out together? You
write, I'll read & tell you what does & doesn't make sense. If I can
understand it, then you probably got the point across :)
Apr 28 '06 #9
Tony wrote:
I have yet to find a good article on 'this'

If you don't come across any, maybe we could work it out together?


This one is a decent start, isn't it?
http://www.quirksmode.org/js/this.html

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Apr 28 '06 #10
On 28/04/2006 19:22, Matt Kruse wrote:
Tony wrote:
I have yet to find a good article on 'this'


If you don't come across any, maybe we could work it out together?


This one is a decent start, isn't it?
http://www.quirksmode.org/js/this.html


I'd give an emphatic, 'No!' It starts with rubbish about 'owners' and
follows with 'copying', which entirely false. Moreover, in an entire
article, it only manages to cover event listeners in any depth, glossing
over, or omitting entirely, the four other circumstances[1] in which the
this operator value changes.

If the this operator is explained well, event listeners should be just a
side note, explained in maybe a paragraph or two with a couple of
examples. The focus should be on other areas.

Mike
[1] See the latter half of my post in "How do I properly pass a
parameter to a parameterized event handler in a loop?" I
didn't cover event listeners, but it would be an extension of
the 'Methods' section.

<http://groups.google.co.uk/group/comp.lang.javascript/browse_frm/thread/d77f3051f3e80a8c/ec26cd885e01c292#ec26cd885e01c292>

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Apr 28 '06 #11
Michael Winter wrote:
On 28/04/2006 00:22, RobG wrote:

[snip]
I have yet to find a good article on 'this',
Of the posts you've read in the archives, and perhaps other on the Web,
in what ways have you found them wanting? Do they provide too much
information? Too little? Do they assume too much background information?
Are they inaccessible (too much technical jargon)? Are there too few
examples?


Searching for 'this' is like trying to search for 'and', you have to
search for related terms that may be used in conjunction, or not. It
takes a lot of wading through posts.

Some of the post I've read are great, but I think to explain how it all
works requires more than just explaining 'this', but also the difference
between global, function and eval code, the creation of execution
objects, scope chains, etc.

I just don't think I can do that in a way that makes sense to someone
else - which indicates that I don't understand it in enough detail.

Writing a good, reusable explanation requires feedback or an outstanding
author.
Or both :-)

Surely there's an article somewhere that, with some tweaking,
would be good enough to serve as a reference document.


I hope there is, but I haven't found it. I'll look at the quirksmode
article suggested by Matt and take your comments on board too. There
are snippets here and there in a variety of posts that help too, I'll
spend some time on it.

I've tried writing one but I can't make it sensible.


You could always post it (or a link) here. You might get suggestions.

Though composition is hardly the focus of this group, I don't see the
harm in contributors who are comfortable with and adept at writing
(which eliminates me :-) helping others in that regard. There's little
point in having knowledge in a group like this if one lacks the ability
to convey it to others.


Your posts are generally lucid and very well written, even people who
post complete trash sometimes do good by provoking responses that are
very helpful to those who may be lurking. It just depends how
thick-skinned you are to be able to cop the flak and keep on posting
regardless!
--
Rob
Apr 29 '06 #12
Matt Kruse wrote:
Tony wrote:
I have yet to find a good article on 'this'


If you don't come across any, maybe we could work it out together?

This one is a decent start, isn't it?
http://www.quirksmode.org/js/this.html


THought I had read every page on quirksmode. Apparantly I'll have to go
back and try again!

Apr 29 '06 #13
On 29/04/2006 11:41, RobG wrote:

[snip]
Searching for 'this' is like trying to search for 'and' [...]
A decent phrase search[1] should eliminate most of the chaff, but I know
what you mean. I purposefully switched to using the phrase "this
operator" partly for that reason.
Some of the post I've read are great, but I think to explain how it all
works requires more than just explaining 'this', but also the difference
between global, function and eval code, the creation of execution
objects, scope chains, etc.


Just thinking aloud... It certainly wouldn't hurt to have detailed
articles on other subjects. Those that understand the concepts can just
keep reading, whilst others can follow links to gain more background
knowledge. However, that's a heck of a lot of writing.

Cheers,
Mike
[1]
<http://groups.google.co.uk/groups/search?q=group%3Acomp.lang.javascript+%22this+oper ator%22+%7C+%22this+refers+%7C+references%22>

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
May 4 '06 #14

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

1 post views Thread by Dave Higgins | last post: by
2 posts views Thread by Bryan Olson | last post: by
10 posts views Thread by Java and Swing | last post: by
1 post views Thread by Homer Simpson | last post: by
110 posts views Thread by Gregory Pietsch | last post: by
3 posts views Thread by Bartholomew Simpson | last post: by
20 posts views Thread by J de Boyne Pollard | last post: by

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.