473,326 Members | 2,438 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 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 1525

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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Dave Higgins | last post by:
Can the GD library do this? I have an array of numbers (which I shall be manipulating server-side), which I wish to convert into an image. The elements of the array are essentially the 1D...
12
by: Leon | last post by:
Hi all. For my application I'm using a third-party library which is supplied as a library file (.lib) and an associated header file to prototype the functions defined in the library. Important...
2
by: Bryan Olson | last post by:
The current Python standard library provides two cryptographic hash functions: MD5 and SHA-1 . The authors of MD5 originally stated: It is conjectured that it is computationally infeasible to...
10
by: Java and Swing | last post by:
I need to write an extension for a C function so that I can call it from python. C code (myapp.c) ====== typedef unsigned long MY_LONG; char *DoStuff(char *input, MY_LONG *x) { ... } so...
1
by: Homer Simpson | last post by:
Hi Everyone, I would like to create a DLL to store my common math functions and then call the DLL from multiple apps. For example, I am creating a function called "Distance" that will return the...
5
by: Bern McCarty | last post by:
I have a DLL written in C++ (it's really C code that was adjusted to compile OK as C++) that I compile successfully into IL with the /CLR switch of Visual C 7.1. I use the resultant library...
110
by: Gregory Pietsch | last post by:
I'm writing a portable implementation of the C standard library for http://www.clc-wiki.net and I was wondering if someone could check the functions in math.h for sanity/portability/whatever. I'm...
3
by: Bartholomew Simpson | last post by:
I am writing some C++ wrappers around some legacy C ones - more specifically, I am providing ctors, dtors and assignment operators for the C structs. I have a ton of existing C code that uses...
20
by: J de Boyne Pollard | last post by:
MThe library functions which are included to allow process Mlaunch, forking, and termination, imply that it is both Mpossible and desirable for a process to fork itself. This is Ma fundamental...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.