九门宁生

导航

js创建对象

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

<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>

<body>

  <script>
    // 1  new Object()
    // var hero = new Object();  // 空对象
    // hero.blood = 100;
    // hero.name = '刘备';
    // hero.weapon = '剑';

    // hero.attack = function () {
    //   console.log(this.weapon + ' 攻击敌人');
    // }

    // 2 对象字面量
    // var hero = {};   // 空对象
    // var hero1 = {
    //   blood: 100,
    //   name: '刘备',
    //   weapon: '剑',
    //   attack: function () {
    //     console.log(this.weapon + ' 攻击敌人');
    //   }
    // }

    // // hero.attack();
    // var hero2 = {
    //   blood: 100,
    //   name: '关羽',
    //   weapon: '刀',
    //   attack: function () {
    //     console.log(this.weapon + ' 攻击敌人');
    //   }
    // }
    // 
    // 3 工厂函数 创建多个对象
    function createHero(name, blood, weapon) {
      var o = new Object();
      o.name = name;
      o.blood = blood;
      o.weapon = weapon;
      o.attack = function () {
        console.log(this.weapon + ' 攻击敌人');
      }
      return o;
    }

    var hero = createHero('刘备', 100, '');
    var hero1 = createHero('关羽', 100, '');
    // console.log(typeof hero);
    console.log(hero instanceof createHero);


    var arr = [];
    console.log(arr instanceof Array);
  </script>
</body>

</html>

 

posted on 2019-08-29 15:26  九门宁生  阅读(160)  评论(0编辑  收藏  举报