Created
April 26, 2020 17:53
-
-
Save Katerina198b/70eb69533409678b26fa9ea637a95226 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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