Skip to content

Instantly share code, notes, and snippets.

@Katerina198b
Created April 26, 2020 17:53
Show Gist options
  • Save Katerina198b/70eb69533409678b26fa9ea637a95226 to your computer and use it in GitHub Desktop.
Save Katerina198b/70eb69533409678b26fa9ea637a95226 to your computer and use it in GitHub Desktop.
const cat = {
name: 'Snowball',
talk() {
console.log('Мяу');
},
getInstance() {
return this;
}
}
const instance1 = cat.getInstance()
const instance2 = cat.getInstance()
console.log(instance1 === instance2) //true
//IIFE
var myCat = (function () {
let instance;
function createInstance() {
const object = {
name: 'Snowball',
talk() {
console.log('Мяу');
}
return object;
}
}
return {
getInstance: function () {
if (!instance) {
instance = createInstance();
}
return instance;
}
};
})();
const instance1 = cat.getInstance()
const instance2 = cat.getInstance()
console.log(instance1 === instance2) //true
//constructor + IIFE
const cat() = !function() {
let intance;
return function() {
if (instance) {
return instance
}
intance = {
name: 'Snowball',
talk() {
console.log('Мяу');
}
return object;
}
this = instance;
}
}
const instance1 = new cat();
const instance2 = new cat();
console.log(instance1 === instance2) //true
//es6
class Cat {
constructor() {
if (Cat.instance) {
return Cat.instance;
}
this.name = "Cнежок";
Cat.instance = this;
}
talk() {
console.log('Мяу');
}
}
const instance1 = new MyCat()
const instance2 = new MyCat()
console.log(instance1 === instance2) //true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment