• 对象的创建方法


    1 对象字面量
    var hero = {
      name: '黄忠',
      weapon: '弓箭',
      equipment: ['头盔', '靴子', '盔甲'],
      blood: 100,
      attack: function () {
        console.log(this.name + ':射箭');
      },
      run: function () {
        console.log(this.name + ': 加速跑');
      }
    }
    console.log(hero.name);
    console.log(hero.equipment);

    hero.attack();
    hero.run();


    2 new Object()
    Object 是一个构造函数
    new 的方式来调用构造函数
    new Object() 调用构造函数 会在内存中创建一个对象
      var hero = new Object(); // 创建了一个空的对象
      // 打印一个不存在的属性 输出 undefined
      // console.log(hero.name);
      // 属性
      // JavaScript的动态特性
      hero.name = '黄忠';
      hero.weapon = '弓箭';
      hero.equipment = ['头盔', '靴子', '盔甲'];
      hero.blood = 100;
      // 方法
      hero.attack = function () {
        console.log(this.name + ': 射箭');
      }
      hero.run = function () {
        console.log(this.name + ': 加速跑')
      }

    3 工厂方法
    function createHero(name, weapon, equipment, blood) {
      var hero = new Object(); //返回一个空的对象
      // 属性
      hero.name = name;
      hero.weapon = weapon;
      hero.equipment = equipment;
      hero.blood = blood;
      // 方法
      hero.attack = function () {
        console.log(this.name + ':攻击');
      }
      hero.run = function () {
        console.log(this.name + ':加速跑');
      }
      return hero;
    }

    var hero1 = createHero('黄忠', '弓箭', ['头盔', '靴子'], 100);
    var hero2 = createHero('刘备', '剑', ['头盔', '盔甲'], 100);


    // 4 自定义构造函数
    // new Object();
    // new Hero();
    // 帕斯卡命名 第一个单词的第一个字母大写,后续的每一个单词的第一个字母都大写
    // 自定义构造函数
    function Hero(name, weapon, equipment, blood) {
    // this 动态的给对象增加成员
    // this 指向了当前对象
      this.name = name;
      this.weapon = weapon;
      this.equipment = equipment;
      this.blood = blood;

      this.attack = function () {
        console.log(this.name + ':攻击');
      }
      this.run = function () {
        console.log(this.name + ': 加速跑');
      }
    }

    var hero1 = new Hero('黄忠', '弓箭', ['头盔', '靴子'], 100);
    var hero2 = new Hero('刘备', '剑', ['头盔', '盔甲'], 100);

  • 相关阅读:
    文件上传漏洞全面渗透姿势总结
    注册frpc为windows服务,可在未登录用户时启动
    SpringIOC 容器注入方式
    如何交换 Integer 的值?
    分布式websocket服务器
    win10安装Hbase2.3.0
    hadoop常用的命令
    win10安装kafka 2.122.8.1
    win10激活码
    win10 flume source为spooldir,输出到hdfs
  • 原文地址:https://www.cnblogs.com/pxxdbk/p/12560974.html
Copyright © 2020-2023  润新知