How to use built-in Map in custom Map in javascript - javascript

I have a class named Map, and I want to define a member variables as built-in Map.
Here is my code.
class Map {
constructor() {
this.myMap = new Map();
}
}
It seems like system will recognize it as a recursive call.
I can use object instead of built-in Map, but I want to use float number as the key.

Refer to window.Map to get the global Map instead of this particular class.
class Map {
constructor() {
this.myMap = new window.Map();
}
}
const m = new Map();
m.myMap.set('foo', 'bar');
console.log('done');

Related

Is there a self pointer to own class?

Is there some kind of "self" pointer to its own class in JavaScript ?
For example this code has a class called "banana".
I always want Objects of Class "Banana" to be added into the variable "BananaInstances", to never loose the pointer of the new object.
so i got to create a function called "CreateBanana()" which pushs every new object of class "Banana" into the BananaInstances-variable.
var BananaInstances = []
class Banana{
constructor() {
size = "huge"
}
}
CreateBanana()
{
SweetBanana = new Banana()
BananaInstances.push(SweetBanana)
}
CreateBanana()
is there a way to avoid a "CreateBanana"-function and let the constructor of Class "Banana" push itself into "BananaInstances" ?
Within a class, the this keyword is the reference to self.
To keep the references of the created instances of a class - directly within a class use the static keyword.
MDN Classes The static keyword defines a static method for a class. Static methods are called without instantiating their class and cannot be called through a class instance. Static methods are often used to create utility functions for an application.
class Banana {
static instances = [];
size = "huge"
constructor(props) {
Object.assign(this, props);
Banana.instances.push(this);
}
}
const b1 = new Banana();
const b2 = new Banana({size: "normal"});
console.log(Banana.instances);
// [Banana{"size": "huge"}, Banana{"size": "normal"}]
Instead of an Array we could also use new Set
The Set Object lets you store unique values of any type, whether primitive values or object references.
Use static instances = new Set;
and than in the constructor use Banana.instances.add(this);
Notice that the above does not provide an out-of-the-box way to track garbage collected, deleted instances. If the necessity or a Finalizer arises, to remove it from the Set, a new class method like destructor() { Banana.instances.delete(this); } might be required.
class Banana {
static instances = new Set();
size = "huge"
constructor(props) {
Object.assign(this, props);
Banana.instances.add(this);
}
destructor() {
Banana.instances.delete(this);
}
}
const b1 = new Banana();
const b2 = new Banana({size: "normal"});
console.log([...Banana.instances]);
// [Banana{"size": "huge"}, Banana{"size": "normal"}]
b1.destructor(); // Call destructor on b1
console.log([...Banana.instances]);
// [Banana{"size": "normal"}]

Get array in other method in the same class in javascript

I have been looking for an answer on here but i couldn't find any, but anyway my question is how to get an array in a method that has been declared and initialised in an other method but in the same class. I'll make it a bit more clear by demonstrating what i want to achieve and what i have tried so far.
Javascript:
class SomeClass {
method1() {
var array = new array();
//its actually a 2d array and it is being initialised here but for simplicity this isn't
//necessary in the example.
}
method2() {
// --> Here i want to access the array and it's contents.
//I have tried this:
this.array;
//and
array;
}
}
but i got "cannot ready property of undefined" when i tried this.array;
You have to declare the array as an element of the Class, not inside a method, for that, you can use a constructor.
In this link you can see more information.
Here is an example:
class SomeClass {
constructor(someValue) {
// Initialize array or any other atribute
this.arr = new Array(someValue);
}
method1() {
console.log(this.arr);
}
method2() {
console.log(this.arr);
}
}
var instance = new SomeClass('data');
instance.method1();
instance.method2();
The array which is declared in method1 will only be available in that function. There is no way to access local variables of a function in some other function.
The solution could be to use the array as property of instance of class
class SomeClass {
constructor(){
this.array = []
}
method1() {
console.log(this.array);
}
method2() {
console.log(this.array)
}
}
const obj = new SomeClass();
obj.method1();
obj.method2();
Okay so you are making a major mistake, Your concepts of OOP are at stake.
To access array as a property/ instance of a class , You need to declare a constructor it within the class. Somewhat like this
class SomeClass {
constructor(){
this.array = new Array();
}
yourMethod1(){
console.log(this.array); /// You cann access it here and manipulate
}
yourMethod2(){
console.log(this.array); // You can accesss here too and do the same
}
}
Later on you can create an instance of your class like this and access the methods and do whatsoever
let a = new SomeClass();
a.yourMethod1();
a.yourMethod2();

How to create an object inside an object in Javascript?

I have a want to create a object Metrics within which I need to initialize various other objects such as StatsD.
I know how to create Metrics object in javascript.
function Metrics(params) {
// initialize params
}
Metrics.prototype.functionName = function() {
}
However I am confused is how to embed an object inside another object and access its methods ?
In java it would be easy:
class Metrics {
StatsD statsD;
}
new Metrics().statsD.increment("foobar");
How would I do the same in javascript ?
You'd do it in the same way as in Java:
function Metrics(params) {
this.statsd = new StatssD();
}
The only difference is that you don't have to declare the attribute with its type - just initialising the property in the constructor is enough.
Just set the property (statsd in this case) to a new object (new StatsD()):
function Metrics(params) {
//Initialize params
this.statsd = new StatsD();
}
You could also attach the StatsD to the prototype:
Metrics.prototype.statsd = StatsD();

How do you call a static method on a custom class? JS

In javascript, I've created a class Group that creates an empty array named items and returns it.
But I'm trying to create a static method from(){} that takes an iterable object and creates a new Group from that iterable obj.
I'm trying this.items.push() but its not working how I'd expect it to
class Group(){
constructor(){
this.items = []
}
from(obj){
for(let item of obj){this.items.push(item)}
}
}
i'd implement it like so:
let group = Group.from([10, 11))//random numbers
it unfortunately returns the following error:
TypeError: Cannot read property 'push' of undefined (line 37 in function
Function.from)
You have a syntax error:
class Group(){
should be:
class Group { // no parameter list here
as in the class syntax, the parameters are defined in the constructor function.
Where a constructor adds methods to "class" instances as below, the method is available to instances, not the constructor itself. You you have to create an instance, then call the method:
class Group {
constructor () {
this.items = [];
}
from (obj) {
for (let item of obj) {
this.items.push(item);
}
}
}
var group = new Group();
group.from([1,2]);
console.log(group.items); // 1, 2
console.log(typeof Group.from); // undefined
Although there are drafts for new static syntax on JS classes, you'll currently need to use the prototype for static methods / properties.
class Group {
constructor(){
this.items = []
}
}
Group.prototype.from = function(obj){
var group = new Group;
for(let item of obj) group.items.push(item);
return group;
}
let group = aGroudInstance.from([10, 11]);
You probably want to simply add the method onto the Group class (object) like so:
Group.from = function(...) ...;
As it's not actually making use of being a static method, and would unnecesarily require an instance of a Group -- unless you used it like so: Group.prototype.from(...).
It's a factory function.

How to construct objects with inner objects

I'm trying to construct an instance of a class using the output from a MongoDB database. My problems lies in that my class has nested classes, which I would also like to instantiate. Using Object.assign() seems to only create a top level object, while the inner properties are still 'object', so I don't have access to their methods. For example
let obj = {address: { street: '1234 Rainbow Road' }};
class Person {
constructor(obj) {
Object.assign(this, obj);
}
}
class Address {
constructor(addr) {
this.address = addr;
}
printAddress() {
console.log(this.address);
}
}
let p = new Person(obj);
p.address.printAddress() // fails, no function printAddress
compared to...
class Person {
constructor(obj) {
this.address = new Address(obj.address);
}
}
class Address {
constructor(addr) {
this.address = addr;
}
printAddress() {
console.log(this.address);
}
}
let p = new Person(obj);
p.address.printAddress() // works
This is just an example, my class is quite a bit larger, is there a way to shorthand instantiate all inner classes as well? Or would I have to decompose it like I did in the second code snippet? Thanks!
You can call new Address in the argument list of new Person
let p = new Person(new Address({street: '1234 Rainbow Road'}));
The second version is good enough as design choice for a single property.
It doesn't look like the case for full-fledged DI container, but if the number of properties is big enough, some kind of class map may help to eliminate boilerplate code.
class Person {
constructor(obj, classMap) {
for (let prop of Object.keys(classMap)) {
this[prop] = new classMap[prop](obj[prop]);
}
}
}
let p = new Person(obj, { address: Address });

Categories

Resources