...

View Full Version : JS variable.doSomething()



Jazzo
12-02-2009, 08:00 PM
I want to create a JS method (I think that's what they're called) where you write variable.doSomething(argument) and the doSomething function can access the variable. But the doSomething method is not tied to a specific object. You can have anything.doSomething() and it will still work. How would that be done?

Thanks,
Jazzo

Kor
12-02-2009, 09:00 PM
I want to create a JS method (I think that's what they're called) where you write variable.doSomething(argument) and the doSomething function can access the variable. But the doSomething method is not tied to a specific object. You can have anything.doSomething() and it will still work. How would that be done?

Thanks,
Jazzo
A method of which object? In order to do what? can you detail a little bit, please?

I guess you need a constructor.
http://www.javascriptkit.com/javatutors/oopjs2.shtml

Jazzo
12-02-2009, 09:16 PM
Well, it's for a JS library so I don't want to have someone else do it for me, but basically this. I am making an inArray function. I want you to be able to do value.inArray(array) and it will return true if the value is in the array. I already coded the function, I just don't know how to set it up that way.

Old Pedant
12-02-2009, 09:32 PM
Array.prototype.inArray = function( val )
{
for ( var i = 0; i < this.length; ++i )
{
if ( this[i] == val ) return true;
}
return false;
}

var x = [ 77, 88, 99 ];
alert( x.inArray(101) );
var y = new Array( "aardvark", "bear", "camel", "dog" );
alert( y.inArray("bear") );


I'm sure you can see how to extend that to allow an array as the argument to the method.

You *CAN* attach the method to the Object prototype, and then test "this" to see if it's an array, but it seems kind of pointless, to me.

Jazzo
12-02-2009, 10:45 PM
Thank you (once again) old pedant!

Jazzo



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum