JavaScript constructor 属性

定义和用法

constructor 属性返回对创建此对象的数组函数的引用。

语法

  1. object.constructor

实例

例子 1

在本例中,我们将展示如何使用 constructor 属性:

  1. <script type="text/javascript">
  2.  
  3. var test=new Array();
  4.  
  5. if (test.constructor==Array)
  6. {
  7. document.write("This is an Array");
  8. }
  9. if (test.constructor==Boolean)
  10. {
  11. document.write("This is a Boolean");
  12. }
  13. if (test.constructor==Date)
  14. {
  15. document.write("This is a Date");
  16. }
  17. if (test.constructor==String)
  18. {
  19. document.write("This is a String");
  20. }
  21.  
  22. </script>

输出:

  1. This is an Array

例子 2

在本例中,我们将展示如何使用 constructor 属性:

  1. <script type="text/javascript">
  2.  
  3. function employee(name,job,born)
  4. {
  5. this.name=name;
  6. this.job=job;
  7. this.born=born;
  8. }
  9.  
  10. var bill=new employee("Bill Gates","Engineer",1985);
  11.  
  12. document.write(bill.constructor);
  13.  
  14. </script>

输出:

  1. function employee(name, job, born)
  2. {this.name = name; this.job = job; this.born = born;}