对象的创建方法

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);

原文地址:https://www.cnblogs.com/pxxdbk/p/12560974.html