javascript access array from another class - javascript

i want to access an array from another class
FirstClass.ts
items:any = [];
export class ContainsDataArray {
saveItems(item){
this.items.push(item);
}
}
SecondClass
export class AccessArrayfromAnotherClass {
(Call the array from the FirstClass this.items to be exact)
}

How about this:
class A {
static array: number[] = [1, 2, 3];
constructor() {}
}
class B {
constructor() {}
getArray() {
console.log(A.array);
}
}
f = new B();
f.getArray();

In Object-Oriented Programming (OOP), you can use composition or inheritance.
Composition
class ContainsDataArray {
constructor() {
this._items = [];
}
saveItem(item) {
this._items.push(item);
}
get items() {
return this._items;
}
}
class AccessArrayfromAnotherClass {
constructor() {
this._ref = new ContainsDataArray();
}
get ref() {
return this._ref;
}
}
let instance = new AccessArrayfromAnotherClass();
instance.ref.saveItem('Foo');
instance.ref.saveItem('Bar');
console.log(instance.ref.items);
Inheritance
class ContainsDataArray {
constructor() {
this._items = [];
}
saveItem(item) {
this._items.push(item);
}
get items() {
return this._items;
}
}
class AccessArrayfromAnotherClass extends ContainsDataArray {}
let instance = new AccessArrayfromAnotherClass();
instance.saveItem('Foo');
instance.saveItem('Bar');
console.log(instance.items);

Related

Nodejs: extends class and change parent variable per child classes

This is my classes:
export class Parent {
protected static name: string;
public getName() {
return Parent.name
}
}
export class Child1 extends Parent {
constructor() {
super()
if (!Child1.name) {
// connect to database for get names
Child1.name = '1';
}
}
}
export class Child2 extends Parent {
constructor() {
super()
if (!Child2.name) {
// connect to database for get names
Child2.name = '2';
}
}
}
I run this code:
let child1 = new Child1()
let child2 = new Child2()
console.log(child1.getName())
console.log(child2.getName())
And I get this result:
undefined
undefined
But I get this result:
1
2
I want to connect to database and get names, so per new class I dont want to connect to database again.
Parent.name will always access the name property of Parent. If you want to make it conditional on which instance the function is called on you have to use this.constructor.name instead:
public getName() {
return this.constructor.name
}
this.constructor refers to the object's constructor function / class.
class Parent {
getName() {
return this.constructor.db
// ^^^^^^^^^^^^^^^^
}
}
class Child1 extends Parent {
constructor() {
super()
if (!Child1.db) {
// connect to database for get names
Child1.db = '1';
}
}
}
class Child2 extends Parent {
constructor() {
super()
if (!Child2.db) {
// connect to database for get names
Child2.db = '2';
}
}
}
let child1 = new Child1()
let child2 = new Child2()
console.log(child1.getName())
console.log(child2.getName())
The problem is static members are bound to the class and can not be referenced via an instance.
Use it like this:
class Parent {
protected static name: string;
public getName() {
return Parent.name
}
}
class Child1 extends Parent {
constructor() {
super()
if (!Parent.name) {
Parent.name = '1';
}
}
}
class Child2 extends Parent {
constructor() {
super()
if (!Parent.name) {
// connect to database for get names
Parent.name = '2';
}
}
}
let child1 = new Child1();
let child2 = new Child2();
console.log(child1.getName());
console.log(child2.getName());
export class Parent {
protected namE: string;
public getName() {
return this.namE
}
}
export class Child1 extends Parent {
constructor() {
super()
if (!this.namE) {
// connect to database for get namEs
this.namE = '1';
}
}
}
export class Child2 extends Parent {
constructor() {
super()
if (!this.namE) {
// connect to database for get namEs
this.namE = '2';
}
}
}
let child1 = new Child1()
let child2 = new Child2()
console.log(child1.getName())
console.log(child2.getName())
OutPut:
1
2
Why don't you do it this way?

Javascript es6 class inheritance

Can someone please explain to me why calling a parent function from child is reseting parent class variables.
class Garages {
constructor() {
this.garages = {};
}
addGarage(id) {
this.garages[id] = {id};
return this.garages[id];
}
getGarage(id) {
alert(this.garages[id]); //why undefined?
}
}
class Cars extends Garages {
constructor() {
super();
this.cars = [];
}
getGarageByID(id) {
this.getGarage(id)
}
}
const cars = new Cars();
const garages = new Garages();
console.log(garages.addGarage("one"))
cars.getGarageByID("one")
FIDDLE
beacuse the instance of cars is differnet from garages , you should write like this:
alert(cars.addGarage("one")) //alerts object
alert(cars.getGarageByID("one"))
Issue #1 is that you are adding to one instance and asking another to get you the value.
Issue #2 is that you are not returning anything from getGarageByID hence you get undefined.
Change your code to this:
class Garages {
constructor() {
this.garages = {};
}
addGarage(id) {
this.garages[id] = {id};
return this.garages[id];
}
getGarage(id) {
return this.garages[id];
}
}
class Cars extends Garages {
constructor() {
super();
this.cars = [];
}
getGarageByID(id) {
return this.getGarage(id)
}
}
const cars = new Cars();
console.log(cars.addGarage("one"))
console.log(cars.getGarageByID("one"))
And you should get both to print.

es6 super propMethod call super other propMethod

I use nodejs 6.10.3 the code is show in below, I have problem for es6 class inheritance.
'use strict';
class Foo {
constructor() {}
hi() {
console.log('foo.hi');
this._hi();
}
_hi() {
console.log('foo._hi');
}
}
class Goo extends Foo {
constructor() {
super();
}
hi() {
console.log('goo.hi');
super.hi();
}
_hi() {
console.log('goo._hi');
}
}
let goo = new Goo();
goo.hi();
the console.log output is this.
// goo.hi
// foo.hi
// goo._hi
But I need to this.
// goo.hi
// foo.hi
// foo._hi
How can I do?
super will initialize this
'use strict';
class Foo {
constructor() {}
hi() {
console.log('foo.hi');
this._hi();
}
_hi() {
console.log('foo._hi');
}
}
class Goo extends Foo {
constructor() {
super();
}
hi() {
console.log('goo.hi');
Foo.prototype.hi();
}
_hi() {
console.log('goo._hi');
}
}
let goo = new Goo();
goo.hi();

Passing a model from PHP/Laravel to ReactJS Fluxible store

In my TaskController.php I have:
namespace Api;
use Repos\EnquiryRepo;
class TaskController extends \BaseController {
protected $repo;
function __construct() {
parent::__construct();
$this->repo = new EnquiryRepo();
}
public function show($enquiryId)
{
if(!$enquiry = $this->repo->findById($enquiryId)) {
return $this->json('That does not exist.', 404);
}
return \View::make('task.index', ['enquiry' => $enquiry]);
}
}
I am totally lost as to how I can pass the $enquiry model into my react store:
EnquiryStore.js
import { EventEmitter } from 'events';
export default class EnquiryStore extends EventEmitter {
constructor() {
super();
this.enquiries = new Map();
this.loading = false;
}
handleEnquiriesData(payload) {
payload.data.enquiries.forEach((enquiry) => {
this.enquiries.set(enquiry.id, enquiry);
});
this.loading = false;
this.emit('change');
}
handleReceiving() {
this.loading = true;
this.emit('loading');
}
getEnquiries() {
return this.enquiries;
}
dehydrate () {
return this.enquiries;
}
rehydrate (state) {
}
}
EnquiryStore.handlers = {
'RECEIVED_ENQUIRIES_DATA': 'handleEnquiriesData',
'RECEIVING_ENQUIRIES_DATA': 'handleReceiving'
};
EnquiryStore.storeName = 'EnquiryStore';
Would I need to somehow echo it out into a JS variable or something? How can I get this to work? The whole point is so that when the page loads I have all the data already and React/Fluxible doesn't need to make another request for the data.
After a bit of trail and error I got it working:
In my Laravel view I did:
#extends('layouts.react')
#section('css')
{{HTML::style('/css/task.css?bust=' . time())}}
#stop
#section('js')
<script>
app_dehydrated.context.dispatcher.stores.EnquiryStore = {{$enquiry}}
</script>
#stop
Then my store:
import { EventEmitter } from 'events';
export default class EnquiryStore extends EventEmitter {
constructor() {
super();
this.enquiry = {};
this.loading = false;
}
handleReceiving() {
this.loading = true;
this.emit('loading');
}
getEnquiry() {
return this.enquiry;
}
dehydrate () {
return this.enquiry;
}
rehydrate (state) {
this.enquiry = state;
}
}
EnquiryStore.handlers = {
'RECEIVED_ENQUIRIES_DATA': 'handleEnquiriesData',
'RECEIVING_ENQUIRIES_DATA': 'handleReceiving'
};
EnquiryStore.storeName = 'EnquiryStore';
If there is a better way please tell me! Hope this helps others.

Javascript - Base class method not available in derived class when extending using lodAsh

I have a base class :
class Base {
constructor() {
this.name = "base_class"
}
getBaseName() {
return "base"
}
}
and a Derived class
var _ = require('lodash');
class Derived {
constructor() {
this.name = "derived"
}
getDerivedName() {
return "derived"
}
}
_.extend(Derived.prototype, Base)
I was expecting to have getBaseName available in the derived class. But its not the case. What should I do for that? What am I missing?
var derived = new Derived();
console.log(derived.getBaseName)
-- undefined
Why are you using lodash to extend ES6 classes? Can't you just use the extends keyword?
class Derived extends Base {
constructor() {
super();
this.name = "derived"
}
getDerivedName() {
return this.name;
}
}

Categories