js new操作符

来源:互联网 发布:2016淘宝女装销量前十 编辑:程序博客网 时间:2024/05/17 03:18
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  2. <html>  
  3. <head>  
  4. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  5. <title>Insert title here</title>  
  6. </head>  
  7. <body>  
  8. <script type="text/javascript">  
  9. /*没有返回值  
  10. function Test1(str) {  
  11.     this.a = str;  
  12. }  
  13. //new  
  14. var myTest1 = new Test1('myTest1');  
  15. alert(myTest1);//object Object  
  16. //no new  
  17. var myTest1 = Test1('myTest1');  
  18. alert(myTest1);//undefined  
  19. */  
  20.   
  21. /*有返回值  
  22. function Test2(str) {  
  23.     this.a = str;  
  24.     return this.a;  
  25. }  
  26. //new   
  27. var myTest2 = new Test2('myTest2');  
  28. alert(myTest2);//object Object myTest2.a就是myTest2  
  29. //no new  
  30. var myTest2 = Test2('myTest2');  
  31. alert(myTest2);//myTest2  
  32. */  
  33.   
  34. /*返回值为new对象  
  35. function Test3(str) {  
  36.     this.a = str;  
  37.     return new String(this.a);  
  38. }  
  39. var myTest3 = new Test3('myTest3');  
  40. alert(myTest3);//String myTest3  
  41. */  
  42.   
  43. /* new this  
  44. function Test4(str) {  
  45.     this.a = str;  
  46. }  
  47. //对象的get_string方法  
  48. Test4.prototype.get_string = function() {  
  49.     return this.a;//this指这个新对象 this.a 新对象的a属性值  
  50. }  
  51. var myTest4 = new Test4('myTest4');  
  52. alert(myTest4.get_string());//myTest4  
  53. */  
  54.   
  55. /*js 伪继承 伪类  
  56. function Test5(str) {  
  57.     this.a = str;  
  58. }  
  59. Test5.prototype.get_Test5String = function() {  
  60.     return this.a;  
  61. }  
  62. var myTest5 = new Test5('myTest5');  
  63. //alert(myTest5.get_Test5String());  
  64. function Test6(str) {  
  65.     this.b = str;  
  66. }  
  67. Test6.prototype = new Test5('myTest5');//必须放在get_Test6String方法前  不然就冲掉了  
  68. Test6.prototype.get_Test6String = function() {  
  69.     return this.b;  
  70. }  
  71. var myTest6 = new Test6('myTest6');  
  72. alert(myTest6.get_Test6String());//myTest6  
  73. alert(myTest6.get_Test5String());//myTest5  
  74. */  
  75. </script>  
  76. </body>  
  77. </html>  
0 0
原创粉丝点击