`

javascript to know the function of the constructed object instance

阅读更多

Javascript is a dynamic type function.  you cannot do something like reflection in other strong langauge. 

 

 

though you cannot do something like typeof(obj), while you can test if a function is the contructor that cretaed the object. 

 

basically you can test if a function is the constructor to an object by two ways

 

 

  1. obj isinstanceof Functin
  2. obj.contructor == Function

 

below is the html file that shows you have to do that.

 

 

<!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 type="text/javascript" src="../unit.js"></script>
    <script type="text/javascript">


      function Ninja() { }
      var ninja = new Ninja();


      window.onload = function () {
        test("object type test", function () {
          assert(typeof ninja == "object", "However the type of the instance is still an object.");
          assert(ninja instanceof Ninja, "The object was instantiated properly.");
          assert(ninja.constructor == Ninja, "The ninja object was created by the Ninja function");
          var ninja2 = new ninja.constructor();
          assert(ninja2 instanceof Ninja, "Still a ninja object.");
        });
      };
    </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