Shared logic between constructor and another function in Java Script - javascript

I have a situation like that:
class TestClass {
constructor() {
shared logic
}
anotherFunction() {
shared logic
}
}
How can I achieve that not duplicating the code?

As always, create a function for the shared logic, either inside of the class or outside of it.
class TestClass {
constructor() {
this.sharedLogicFunction();
}
anotherFunction() {
this.sharedLogicFunction();
}
sharedLogicFunction() {}
}

Put your code to the anotherFunction() and call this function from constructor.
class TestClass {
constructor() {
this.anotherFunction();
}
anotherFunction() {
here is some logic to do
}
}

Related

Pass parameters through scene.switch() in phaser 3?

Is there a way to pass data through the scene.switch() function? I've seen this in other scene changing functions, but not this one and I don't know how to receive the data. How could I do that if my code looks something like this, where message is the second parameter passed through scene.switch() function.
class MyScene1 extends Phaser.Scene {
constructor() {
super('scene1')
}
create() {
this.scene.switch('scene2', 'greetings from scene 1')
}
}
class MyScene2 extends Phaser.Scene {
constructor() {
super('scene2')
}
create() {
// Set message to the value that was passed through scene.switch()
console.log(message)
}
}
Ok, so I did some research and it turns out you can do this in the init() function, like so:
class MyScene1 extends Phaser.Scene{
constructor(){
super('scene1')
}
create(){
this.scene.switch('scene2', 'greetings froms scene 1')
}
}
class MyScene2 extends Phaser.Scene{
constructor(){
super('scene2')
}
init(message){
console.log(message)
}
}

Calling parent constructor in javascript

Wonder if anyone can help?
I'm trying to call a parent's constructor or at a minimum get a reference to the parent class in some way without hardcoding anything.
class A {
static foo(options) {
parent::__construct(options); <- this is how you would get the parent in php
}
}
class B extends A {
}
Is this possible?
In a javascript class (and OOP in general), a static method is not part of an instance and therefore the object it resides in does not have a constructor.
You should avoid using static method for this sort of thing and use a standard constructor and call super() to call the parent constructor.
class A {
constructor(options) {
console.log('Options are:');
console.log(options);
}
}
class B extends A {
constructor(options) {
super(options);
}
}
const item = new B({item1: 'abc'});
Further reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/super
You can use super() to call parent constructor
class A {
constructor() {
console.log('I\'m parent ');
}
foo(){
console.log('Class A: Called foo');
}
}
class B extends A {
constructor() {
super();
}
foo(){
super.foo()
}
}
const b = new B();
b.foo();

How to decorate a Web Component class

I'm creating a #Component decorator that intercedes the constructor of a class to carry out some work after construction. As can be seen in the following code, the work is implemented in an init method.
export function Component (Cls) {
function Class (...args) {
let self = new Cls (...args); // (1)
init (self, ...args);
return self;
}
Class.prototype = Cls.prototype;
return Class;
}
When I test this code on a regular class all works fine. This is a working example:
class Base { ... }
#Component
class Core extends Base {
constructor () {
super (); // init is invoked
}
fx () { console.log ('Core.fx') }
fy () { console.log ('Core.fy') }
}
Nevertheless, when I try to decorate a web component a TypeError: Illegal constructor message is obtained.
#Component
class Core extends HTMLElement {
constructor () {
super ();
}
fx () { console.log ('Core.fx') }
fy () { console.log ('Core.fy') }
}
customElements.define ('x-core', Core);
let coreX = document.createElement ('x-core');
document.body.appendChild (coreX);
I realise the problem is that HTMLElement's do not support direct construction through new operator - see (1) on first listing - but I need a procedure to decorate constructor of any class even though they are custom elements.
Some Idea?
Working Settings: Chrome 68 ยท Babel 7.0.0-beta.51 with babel-plugin-transform-decorators-legacy
You can return a class to avoid direct new.
function Component(cls) {
class c extends cls {
constructor() {
super()
console.log(this)//init
}
}
return c
}

spying on/mocking super class methods in es6

The below are examples but get at the gist of my problem ...
super class:
class Parent {
constructor(a) {
this._a = a;
}
doSomething() { ... implementation... }
}
child-class:
class Child extends Parent {
constructor() {
super('a');
}
doSomethingElse() { return super.doSomething(); }
}
I am using these classes in Angular, so the Parent class is DI'ed into the factory which provides the Child class, something like this:
function ChildDeps(Parent) {
return class Child extends Parent {
... Child class implementation here ...
};
}
ChildDeps.$inject = ['Parent']
Naively, I first tried something like this inside a provide before each clause:
beforeEach(module($provide => {
parent = {
doSomething: jasmine.createSpy('parent.doSomething')
};
Parent = jasmine.createSpy('Parent').and.returnValue(parent);
$provide.value('Parent', Parent);
}));
But this did not work ... saying that spy 'Parent' was never called.
Currently using jasmine/karma for testing. How can mock/spy the super class so I can make expectations about what the Parent class' constructor is called with and that the super.doSomething function is called?
Thanks!

Inheritance method call triggers Typescript compiler error

I am having an issue with webstorm typescript compiler. I have the following classes
export class rootData{
id:string
//...
constructor(){
//...
}
insert = ():Promise<any> =>{
//...
}
}
class child extends rootData {
//...
constructor(){
super();
}
insert = ():Promise<any> => {
return super.insert();
}
}
So typing "super", I see all rootData public methods in the intellisense. But after setting super.insert(), I get the following error :
TS2340: Only public and protected methods of the base class are accessible via the 'super' keyword
Tried in TS playground, it is working (simplified version thought).
Thanks for your help.
EDIT: After checking the compiled javascript, the call of the super method is there. So the compiler gives an error but compiles...
Because super calls are redirected to the prototype you cannot use a property and need to use a method i.e. can't use = ()=>.
Fixed code:
export class rootData{
id:string
//...
constructor(){
//...
}
insert():Promise<any>{
//...
}
}
class child extends rootData {
//...
constructor(){
super();
}
insert():Promise<any> {
return super.insert();
}
}
You could create an "internal" method that is protected that actually performs the logic. Since you can't call it outside of the class, the this will always be in the correct context.
export class rootData{
id:string
//...
constructor(){
//...
}
insert = ():Promise<any> =>{
return this.insertInternal();
}
protected insertInternal():Promise<any>{
//...
}
}
class child extends rootData {
//...
constructor(){
super();
}
protected insertInternal():Promise<any> {
return super.insertInternal();
}
}
You can view a TypeScript Playgound version of it here.

Categories

Resources