 |
|
|
| View previous topic :: View next topic |
| Author |
Message |
swz
Joined: 11 Feb 2008 Posts: 3
|
Posted: Fri Mar 07, 2008 2:03 am Limit the parameters that can be passed to a function |
|
|
|
Hi,
is there a way to limit what can be passed as an argument in a function?
For example:
| Code: |
function myFunction (type)
{
//do something;
} |
I want type to be either a predefined str1 or str2. |
|
ogsolution
Joined: 26 Dec 2007 Posts: 144
|
Posted: Fri Mar 07, 2008 2:19 am |
|
|
|
something like this?
| Code: |
<script type="text/javascript">
var a = "abc";
function action(type){
alert(type);
}
action(a);
</script>
|
|
|
kanenas

Joined: 14 Dec 2004 Posts: 191
|
Posted: Sun Mar 16, 2008 1:23 am Test for object type |
|
|
|
As javascript is weakly typed, you'll have to enforce argument type yourself, something like:
| Code: |
function isa(obj, type) {
if (typeof(obj) == type
|| obj.constructor == type)
{
return true;
}
return false;
}
function foo(arg) {
if (!(isa(arg, str1) || isa(arg, str2))) {
throw({what: "Argument of 'foo(arg)' must be a str1 or str2.",
argument: arg});
}
// process arg
} |
Note that my solution isn't compatible with inheritance. In particular, the 'isa' function fails when obj's class inherits; the types it fails on depends on the javascript implementation. Fixing 'isa' depends on how you implement inheritance. |
|
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
|
|
|
|
 |
|
|
|
|
|
|
|