'what is the difference between an OOP object.instance.function and OOP object.function in JS?
I would like to understand what will be the difference in JS if I will call a function from an OOP including "instance" before calling the key/instance inside.
EDIT after solved:
I need to use the class as singleton but as @VLAS answer below when you export the class as default and add new it will make it singleton automatically. here is the syntax:
class Person {
...
}
export default new Person() //this syntax should make it singleton
the code before the edit for the explain of my issue:
import Person from './personManager';
const person = new Person()
person.introduceSelf()
person.instance.introduceSelf()
I think its a syntax from ES5 that now in ES6 we are don't need any more? or there is something more complex that I didn't understand?
in our project we have this code I just added the personManager.js for the example:
syngletonSymbol.js
/* eslint-disable */
let SingletonSymbol;
if (!SingletonSymbol) {
SingletonSymbol = (function (Object) {
let ObjectPrototype = Object.prototype,
defineProperty = Object.defineProperty,
prefix = `__simbol${Math.random()}__`,
id = 0;
function get() { /* avoid set w/out get prob */ }
function SingletonSymbol() {
const __symbol__ = prefix + id++;
defineProperty(
ObjectPrototype,
this._ = __symbol__,
{
enumerable: false,
configurable: false,
get, // undefined
set(value) {
defineProperty(this, __symbol__, {
enumerable: false,
configurable: true,
writable: true,
value
});
}
}
);
}
defineProperty(SingletonSymbol.prototype, 'toString', {
enumerable: false,
configurable: false,
writable: false,
value: function toString() {
return this._;
}
});
return SingletonSymbol;
}(Object));
}
export default SingletonSymbol;
singleton.js
/* eslint-disable */
const SingletonSymbol = require('./singletonSymbol');
export default class Singleton {
static get instance() {
if (!this[SingletonSymbol]) {
this[SingletonSymbol] = new this();
}
return this[SingletonSymbol];
}
constructor() {
const Class = new.target ? new.target : this.constructor;
if (!Class[SingletonSymbol]) {
Class[SingletonSymbol] = this;
}
return Class[SingletonSymbol];
}
}
personManager.js
import Singleton from 'infrastructure/helpers/singleton';
class Person extends Singleton{
name;
constructor() {
super()
this.name = 'John';
this._init();
}
_init = () => {
this.name = 'Mario';
}
introduceSelf() {
console.log(`Hi! I'm ${this.name}`);
}
}
I will appreciate any answer that will help me to understand the idea and if all that singleton is something that is deprecated and can be deleted from my project
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
