老师,这两种say的方法哪种正确呢,写在constructor外的不是可以节省空间吗

来源:3-3 编程练习

郫县陈冠希

2022-03-07 04:46:22

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    /*
      function Person(name, age) {
          this.name = name;
          this.age = age;
          this.say = function() {
               console.log(this.name, this.age)
          }
      }
      Person.prototype.run = function() {
          console.log("run")
      }
      Person.intro = "this is a Person class"
      Person.show = function() {
          console.log('show')
      }
  */


    class Person {
      constructor(name, age) {
        this.name = name
        this.age = age
        this.say = function () {
          console.log(`我是${this.name},我今年${this.age}岁了`);
        }
      }
      // say() {
      //   console.log(`我是${this.name},我今年${this.age}岁了`);
      // }
      run() {
        console.log("run")
      }

      static intro = 'this is a Person class'
      static getIntro() {
        return 'this is a Person class'
      }

      static show() {
        console.log('show')
      }
    }

    const c = new Person('ZhangSan', 18)
    const c2 = new Person('ls', 18)
    console.log(c.name);
    console.log(c.age);
    c.say()
    c.run()
    Person.show()
    // console.log(Person.intro);
    console.log(Person.getIntro());
  </script>
</body>

</html>
           
下载视频          
写回答

1回答

好帮手慕慕子

2022-03-07

同学你好,写在constructor外确实可以节省空间,但是,当前练习要求是将构造函数改成class写法,构造函数中的say方法是添加到实例对象上的,所以改写为class写法,下面这种方法是对的

https://img.mukewang.com/climg/622571fb0968481c08830473.jpg

祝学习愉快~


0

0 学习 · 17877 问题

查看课程