JavaScript中创建对象的几种方式

野性酷女 2022-08-09 05:29 361阅读 0赞
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
  5. <title>无标题文档</title>
  6. </head>
  7. <body>
  8. <!--创建js对象的第一种方式:使用对象字面量的方式{} 创建一个对象(最简单,好理解,推荐使用)-->
  9. <script>
  10. var Cat={};//JSON
  11. Cat.name="风恋绝尘、";//添加属性并赋值
  12. Cat.age=22;
  13. Cat.sayHello=function(){
  14. alert("hello"+Cat.name+",今年"+Cat["age"]+"岁了");//可以使用"."的方式访问属性,也可以使用HashMap的方式访问
  15. }
  16. Cat.sayHello();//调用对象的方法(函数)
  17. </script>
  18. <!--用function(函数)来模拟class(无参构造函数)-->
  19. <script>
  20. function Person(){
  21. }
  22. var personOne=new Person();//定义一个function,如果有new关键字去"实例化",那么该function可以看做是一个类
  23. personOne.name="梦想之舟";
  24. personOne.hobby="正在敲代码";
  25. personOne.work=function(){
  26. alert(personOne.name+"is"+personOne.hobby);
  27. }
  28. personOne.work();
  29. </script>
  30. <!---用有参数构造函数来实现,这样定义更方便,扩展性更强(推荐使用)-->
  31. <script>
  32. function Pet(name,age,hobby){
  33. this.name=name;//this作用域:当前对象
  34. this.age=age;
  35. this.hobby=hobby;
  36. this.eat=function(){
  37. alert("我叫"+this.name+",我今年"+this.age+"岁了,我喜欢"+this.hobby);
  38. }
  39. }
  40. var hehe=new Pet("王鹏程",22,"打篮球");//实例化创建对象
  41. hehe.eat();
  42. </script>
  43. <!--使用工厂方式来创建对象(Object关键字)-->
  44. <script>
  45. var wcDog = new Object();
  46. wcDog.name="旺财";
  47. wcDog.age=3;
  48. wcDog.work=function(){
  49. alert("我是"+wcDog.name+"汪汪汪......"+"我今年"+wcDog.age+"岁了");
  50. }
  51. wcDog.work();
  52. </script>
  53. <!--使用原型对象的方式 prototype关键字-->
  54. <script>
  55. function Dog(){
  56. }
  57. Dog.prototype.name="旺财";
  58. Dog.prototype.eat=function(){
  59. alert(this.name+"是个吃货");
  60. }
  61. var wangcai = new Dog();
  62. wangcai.eat();
  63. </script>
  64. <!--混合模式(原型和构造函数)-->
  65. <script>
  66. function Car(name,price){
  67. this.name=name;
  68. this.price=price;
  69. }
  70. Car.prototype.sell=function(){
  71. alert("我是"+this.name+",我现在卖"+this.price+"万元");
  72. }
  73. var camry = new Car("凯美瑞呀",22);
  74. camry.sell();
  75. </script>
  76. <!--动态原型的方式(可以看做是混合模式的一种特例)-->
  77. <script>
  78. function Car(name,price){
  79. this.name=name;
  80. this.price=price;
  81. if(typeof Car.sell=="undefined"){
  82. Car.prototype.sell=function(){
  83. alert("我是"+this.name+",我现在卖"+this.price+"万元");
  84. }
  85. Car.sell = true;
  86. }
  87. }
  88. var camry = new Car("凯美瑞呀",33);
  89. camry.sell();
  90. </script>
  91. </body>
  92. </html>

发表评论

表情:
评论列表 (有 0 条评论,361人围观)

还没有评论,来说两句吧...

相关阅读