Can this structure be called closure?

  function Student(n) {
    let name = n;
    this.say = function () {
      console.log(name)
    }
  }
  let xiaoming = new Student("xiaoming")
  let xiaohong = new Student("xiaohong")
  xiaoming.say()
  xiaohong.say()
  function Student(n) {
    this.name = n;
    this.say = function () {
      console.log(this.name)
    }
  }
  let xiaoming = new Student("xiaoming")
  let xiaohong = new Student("xiaohong")
  xiaoming.say()
  xiaohong.say()

both lines of code output are:
xiaoming
xiaohong
so what"s the difference between them? Where is the variable let name stored?
does the first code snippet make the output different because of the closure?

Jun.14,2022

  1. the difference between the above two pieces of code: the name in the first paragraph of code is private and cannot be directly accessed by the outside world. In the second section of the code, the name is Public, and the outside world can modify it directly in the form of xiaoming.name= "xxxx".
  2. these two pieces of code output different names, which has nothing to do with the closure mechanism, but two different instances, and the output name is of course different.
  3. The first piece of code in
  4. is really a closure: access to private variables through public's methods.

the first name is an internal variable and can only be used internally. The name of the second
can only be obtained indirectly by calling the say method. You can call xiaoming.name to get the
let name, which opens up a section of memory space during instantiation, and then stores the closure of the first paragraph of
in order to obtain the internal variables indirectly. The second paragraph is superfluous. You can use xiaoming.name

directly.
Menu