[removed] function returning an object

前端 未结 5 1259
一个人的身影
一个人的身影 2020-12-07 08:36

I\'m taking some JavaScript/jQuery lessons at codecademy.com. Normally the lessons provide answers or hints, but for this one it doesn\'t give any help and I\'m a little con

5条回答
  •  离开以前
    2020-12-07 08:51

    Both styles, with a touch of tweaking, would work.

    The first method uses a Javascript Constructor, which like most things has pros and cons.

     // By convention, constructors start with an upper case letter
    function MakePerson(name,age) {
      // The magic variable 'this' is set by the Javascript engine and points to a newly created object that is ours.
      this.name = name;
      this.age = age;
      this.occupation = "Hobo";
    }
    var jeremy = new MakePerson("Jeremy", 800);
    

    On the other hand, your other method is called the 'Revealing Closure Pattern' if I recall correctly.

    function makePerson(name2, age2) {
      var name = name2;
      var age = age2;
    
      return {
        name: name,
        age: age
      };
    }
    

提交回复
热议问题