【 js 】 构造函数返回的注意事项

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title></title>
  </head>
  <body>
    <article>
      <h1>构造函数返回的注意事项</h1>
      <ul>
        <li>
          如果构造函数中不包括return表达式,则返回
          <strong>this对象</strong>
        </li>
        <li>
          如果构造对象中 return 返回的不是一个对象,也返回
          <strong>this对象</strong>
        </li>
        <li>
          如果构造函数中包括return表达式且return后跟着一个对象。 则会返回
          <strong>return指定的对象</strong>
        </li>
      </ul>
    </article>

    <script>
      // 1. 不包含 return 时 ,返回 this
      function Animal(name) {
        this.name = name;
      }
      let dog = new Animal("");
      console.log(dog.name);

      // 2. 包含 return , 但不是返回的对象时
      function Game(name) {
        this.name = name;
        return "hello";
      }
      let lol = new Game("英雄联盟");
      console.log(lol.name);

      // 3. 包含 return ,且 return 返回的是 对象 时
      function Car(name){
          this.name = name;
          return {
              name : "hello"+name
          }
      }
      let bc = new Car("奔驰");
      console.log(bc.name);
    </script>
  </body>
</html>

 

posted @ 2020-11-29 16:27  武卡卡  阅读(107)  评论(0编辑  收藏  举报