1.2.5.3.危險小叮嚀:「new 」與函數

  • 如果忘記放上new關鍵字, JavaScript會直接執行物件, 此物件會被設為undefined

  • 因此習慣上會把要當成建構子的函數首字大寫

      //建立物件
      function Person() {
          this.firstname = 'John';
          this.lastname = 'Doe';
          }
      //建立空物件
      //呼叫person, 並把this指到person上
      var john = Person();
      //印出undefined
      console.log(john)
      //出現錯誤
      Person.prototype.getFullName = function() {
          return this.firstname + ' ' + this.lastname
      }

Last updated