HTML Tutorial


 Forum HomeForum Home   FAQFAQ   SearchSearch   MemberlistMemberlist   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 
RegisterRegister - Not registered yet? Got something to say? Join HTML Code Tutorial!
Limit the parameters that can be passed to a function
Post new topic   Reply to topic    HTML Help Forum Index -> Javascript
View previous topic :: View next topic  
Author Message
swz



Joined: 11 Feb 2008
Posts: 3

PostPosted: Fri Mar 07, 2008 2:03 am     Limit the parameters that can be passed to a function Reply with quote

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

PostPosted: Fri Mar 07, 2008 2:19 am     Reply with quote

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

PostPosted: Sun Mar 16, 2008 1:23 am     Test for object type Reply with quote

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.
Display posts from previous:   
Post new topic   Reply to topic    HTML Help Forum Index -> Javascript All times are GMT - 8 Hours
Page 1 of 1

 
Jump to:  
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
HTML Help Archive
Powered by phpBB © 2001, 2005 phpBB Group
HTML Help topic RSS feed 

 
HOSTING / DESIGN
MAKE MONEY

Home
  |   Tutorials   |   Forum   |   Quick List   |   Link Directory   |   About
Copyright ©1997-2002 Idocs and ©2002-2007 HTML Code Tutorial