Forum Moderators: open

Message Too Old, No Replies

Defining functions for objects

How is it done?

         

adni18

4:09 am on Nov 27, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Okay. We all know that in javascript, objects have functions that can be performed on them by default, like toString(), but how can a function be assigned to an abstract object (
adni18=new Object();
)?

Bernard Marx

9:33 am on Nov 27, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



JS functions are objects like any other, so you assign methods like you would properties. In fact, until you come to actually attempt to make a call on one, objects don't make any real distinction between their members - properties/methods - they are all treated the same.

If you are not using a function literal, then make sure that the function has been defined prior to assignment.

[pre]
function hello()
{
alert(this.message);
}

[blue]// A[/blue]
adni = new Object();
adni.message = "I'm Adni";
adni.hi = hello;
adni.bye = function(){ alert("I'm off now.")}

[blue]
//
//* or B object literal (aka 'initializer')[/blue]
adni =
{
message : "I'm Adni",
hi : hello,
bye : function(){ alert("I'm off now.")}
}
[/pre]

Do it this way, and all objects will have the method:

[pre]

Object.prototype.hi = hello;
bernard = { message:'Good Morning'}
bernard.hi();[/pre]

In IE, all Javascript objects will have the method.
In Moz, ALL objects will have the method.

You can also override the toString method, which can be handy - especially for debugging.

adni18

1:34 pm on Nov 28, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Thanks.