1、对象自变量方法 较为简便
var hero = {
name:'黄忠',
weapon: '弓箭',
equiment: ['弓箭','靴子','盔甲'],
attack: function () {
console.log(this.name + ':射箭');
},
run: function () {
console.log(this.name + ':加速跑');
}
}
//引用
console.log(hero.name);
console.log(hero.equiment);
hero.attack();
hero.run();
2、new Object() Object一个构造函数 new 用来调用构造函数 对比上一个方法此方法属性和方法个数可以随时改动
var hero = new Object(); /!*创建了一个空的对象*!/
hero.name = '黄忠'; /!*设置属性*!/
hero.weapon = '弓箭';
hero.equipment = ['头盔','靴子','盔甲']; /!*设置方法*!/
hero.attack = function () {
console.log(this.name + ':射箭');
}
hero.run = function () {
console.log(this.name + ':加速跑');
}
//引用
console.log(hero.name);
console.log(hero.equipment);
hero.attack();
hero.run();
3、工厂方法 此方法使用于多个对象具有相同的属性和方法
function createHero(name, weapon, equipment, blood) {
var hero = new Object();
hero.name = name;
hero.weapon = weapon;
hero.equipment = equipment;
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、自定义构造函数 和上个方法一样都是用于多个对象具有相同的属性和方法 但比上一个方法更简洁
function Hero(name,weapon,equipment,blood) {
// this 动态的给对象增加成员
// this 指向了当前对象
this.name = neme;
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);