Skip to content

Instantly share code, notes, and snippets.

@severuykhin
Created June 25, 2017 17:54
Show Gist options
  • Select an option

  • Save severuykhin/f517116c3f98bf9761ab3a8c68f6e183 to your computer and use it in GitHub Desktop.

Select an option

Save severuykhin/f517116c3f98bf9761ab3a8c68f6e183 to your computer and use it in GitHub Desktop.
JavaScript patterns practice
/*********************************************
*
* Strategy
*
**********************************************/
const weapons = {
sword: {
'name': 'Excalibur',
'damage': 20
},
axe: {
'name': 'Big Axe',
'damage': 15
},
knife: {
'name': 'little knife',
'damage': 5
}
};
function Character() {
this.weaponName = null;
this.weaponDamage = null;
};
Character.prototype.setWeapon = function(weapon) {
this.weaponName = weapon['name'];
this.weaponDamage = weapon['damage'];
};
Character.prototype.useWeapon = function() {
if (this.weaponName === null || this.weaponDamage === null) {
console.log(`${this.name} is unarmed`);
} else {
console.log(`${this.name} used ${this.weaponName} and it made ${this.weaponDamage} damage`);
}
};
function Knight(name) {
this.name = name || 'Artur';
};
Knight.prototype = new Character();
function Troll(name) {
this.name = name || 'Gtahllsue';
};
Troll.prototype = new Character();
let knight1 = new Knight();
let troll1 = new Troll();
knight1.useWeapon();
troll1.useWeapon();
knight1.setWeapon(weapons.sword);
troll1.setWeapon(weapons.axe);
knight1.useWeapon();
troll1.useWeapon();
/*********************************************
*
* Singleton
*
**********************************************/
//Вариант 1
const object1 = {
name: 'Object 1'
};
const object2 = {
name: 'Object 2'
};
//Вариант 2
function Single() {
Single.instance;
if (typeof Single.instance == 'object') {
return Single.instance;
};
this.name = 'Big cat';
this.isCat = true;
Single.instance = this;
};
const obj1 = new Single();
const obj2 = new Single();
console.log(obj1 == obj2); //true
//Вариант 3
const Singleton = (function(){
let instance;
return function CreateSingle() {
if (instance) {
return instance;
}
this.name = 'Vasya';
this.age = '25';
if (this && this.constructor === CreateSingle) {
instance = this;
} else {
return new CreateSingle();
}
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment