`

javascript instantiation and arguments.callee

阅读更多

in the nutshell, it is no difference between a constructor and function, because a constructor is essentially a function.

 

however, if you just give user a raw constructor, there is no way for the user to mistakenly call it like a normal function. and the consequence is sometimes horrible.

 

 

e.g 

function User(first, last){
  this.name = first + " " + last;
}
var name = "Resig";
var user = User("John", name);
assert( name == "John Resig", "The name variable is accidentally overridden." );

 

 

How to avoid such kind of thing, here is one deal.

 

/**************************************
*@Summary
* Make sure that the constructor is called in the right way 
*
* Make use of the arguments.callee trick; After this trick, you can find the User function behave like a constructor and a static constructor at the same time.
*
* @Usage:
*   

var name = "Resig";
var user = User1("John", name);
assert( name == "John Resig",
"The name variable is accidentally overridden." );


now, what you can do is to do this :

var name = "Resig";
var user = User("John", name);
assert(user, "This was defined correctly,even if it was by mistake");

* @TODO:
* test it 
***************************************/


function User1(first, second) {
  this.name = first + " " + second;
}


function User(first, second) {

  if (!(this  instanceof arguments.callee)) {
    return new User(first, second);
  }

  this.name = first + " " + second;
}
 

 

 

the statement, 'this instanceof arguments.callee will test if the 'this' is of the type of the callee, in this case, "User", and if it is, just run the constructor as normal (the else part), however, if 'this' is not the 'User', it will instead call and return the constructor.

 

 

 

 

below is the html script that test the function. HTH.

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="instantiation.js" type="text/javascript"></script>
    <script src="../unit.js" type="text/javascript"></script>
    <script type="text/javascript">
      window.onload = function () {
        test("test the instantiation of the function", function () {
          var name = "Resig";
          var user = User("John", name);

          assert(user, "This was defined correctly,even if it was by mistake");
        });
      };
    </script>
    <style type="text/css">
      #results li.pass { color: Green }
      #results li.fail { color: Red }
    </style>
</head>
<body>
<ul id="results" />
</body>
</html>
 

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics