example_of_js_5.html 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title>类和对象</title>
  6. </head>
  7. <body>
  8. <script>
  9. class Person {
  10. constructor(name, age) {
  11. this.name = name
  12. this.age = age
  13. }
  14. eat(food) {
  15. alert(`${this.name}正在吃${food}`)
  16. }
  17. watchAv() {
  18. if (this.age < 18) {
  19. alert(`${this.name}只能看《熊出没》`)
  20. } else {
  21. alert(`${this.name}正在观看岛国爱情动作片`)
  22. }
  23. }
  24. }
  25. let person = new Person('骆昊', 39)
  26. person.eat('蛋炒饭')
  27. let person2 = new Person('王大锤', 15)
  28. person2.watchAv()
  29. // 构造器函数
  30. /*
  31. function Person(name, age) {
  32. this.name = name
  33. this.age = age
  34. }
  35. Person.prototype.eat = function(food) {
  36. alert(this.name + '正在吃' + food)
  37. }
  38. Person.prototype.watchAv = function() {
  39. if (this.age < 18) {
  40. alert(this.name + '只能看《熊出没》')
  41. } else {
  42. alert(this.name + '正在观看岛国爱情动作片')
  43. }
  44. }
  45. let person = new Person('骆昊', 39)
  46. person.eat('蛋炒饭')
  47. let person2 = new Person('王大锤', 15)
  48. person2.watchAv()
  49. */
  50. // JSON - JavaScript Object Notation
  51. // JavaScript对象表达式 - 创建对象的字面量语法
  52. /*
  53. const person = {
  54. name: '骆昊',
  55. age: 39,
  56. eat: function(food) {
  57. alert(this.name + '正在吃' + food)
  58. },
  59. watchAv: function() {
  60. if (this.age < 18) {
  61. alert(this.name + '只能看《熊出没》')
  62. } else {
  63. alert(this.name + '正在观看岛国爱情动作片')
  64. }
  65. }
  66. }
  67. // person.age = 15
  68. person.eat('蛋炒饭')
  69. person.watchAv()
  70. */
  71. </script>
  72. </body>
  73. </html>