ES6 Extending BaseClass without calling constructor and when I am trying to call a method in my subclass throwing error - ecmascript-6

Extending BaseClass without calling constructor and when I am trying to call a method in my subclass throwing error
class BaseClass {
constructor(cfg) {
// Transfer all properties to class object
Object.assign(this, cfg);
if(this.el instanceof HTMLElement === false) {
return;
}
this.setup();
}
setup() {
this.isSetup = true;
}
}
Do I need to call constructor to access this object in current class ?
class MyClass extends BaseClass {
setup() {
// Calling super
super.setup();
this.show(); **// this.show is not a function**
}
show = () => {
console.log('called');
}
}

Related

Calling function of a subclass of Immutable.Map throws 'xxx is not a function' exception

I have created a new class this way:
import Immutable from 'immutable';
export default class Faq extends Immutable.Map {
getState(faqNum) {
return this.get(faqNum) || false;
}
setState(faqNum, open) {
return this.set(faqNum, open);
}
}
But when I call getState on an instance of Faq, it throws an exception faqState.getState is not a function exception?
Why it does not work?
As it turns out Immutable-js does not support class inheritance. (https://github.com/facebook/immutable-js/issues/301)

Construction of generic type parameter in Haxe

I'm trying to instantiate a class based on a function type parameter.
Although the documentation says it is possible, I can't make it work.
Consider the following code:
// Dialog base class
// Every dialog in my application will derive from this
class Dialog
{
public function new()
{
// do some stuff here
}
}
// One of the possible dialogs in the application
// Extends Dialog
class TestDialog extends Dialog
{
public function new()
{
super();
// do some more stuff
}
}
// A simple class that tries to instantiate a specialized dialog, like TestDialog
class SomeAppClass
{
public function new()
{
var instance = create(TestDialog);
}
#:generic
function create<T:Dialog>(type:Class<T>):T
{
return new T();
}
}
This doesn't work with the following error:
create.T does not have a constructor
Clearly, I'm doing something wrong, but what?
SpecialDialog could have a different constructor than Dialog.
So you have to constraint it and then also constraint to Dialog.
Code # Try Haxe
package;
typedef Constructible = {
public function new():Void;
}
// Dialog base class
// Every dialog in my application will derive from this
class Dialog
{
public function new()
{
trace("dialog");
}
}
class SuperDialog extends Dialog
{
public function new()
{
super();
trace("super dialog");
}
}
// A simple class that tries to instantiate a specialized dialog, like TestDialog
class SomeAppClass
{
public function new()
{
var dialog = create(Dialog);
var superDialog = create(SuperDialog);
}
#:generic
public static function create<T:(Constructible,Dialog)>(type:Class<T>):T
{
return new T();
}
}
class Test {
static public function main() {
new SomeAppClass();
}
}

Action Script 3 Static Method

I'm new to Action-script OOP and i need to know how to chain methods like this example i have
I.$(button).bind('click',clickButton).bind('rollover',overButton).bind('rollout',outButton)
First i need to remove the I. to use dollar sign only like jQuery :) to select MovieClip and apply any action on it second issue that i have because this way i'm using static Methods Action-script restrict's me to use only static property saving the last one who called the action here is the class code to know what i mean:
package com.MAIN
{
import flash.display.Sprite;
import flash.events.MouseEvent;
public class I extends Sprite
{
private static var cSelector:Sprite;
public static function $(selector:Sprite)
{
cSelector = selector
return I;
}
public static function alpha(val:Number)
{
cSelector.alpha = val;
return I;
}
// bind mouse event to the element
public static function bind(EventStr,func:Function)
{
var func1:Function = function(e:MouseEvent){
func(cSelector);
}
// select the event from the list
if(typeof(EventStr) == 'string'){
// map the events in lowercase
var events:Object = {click:'CLICK',rollover:'ROLL_OVER',rollout:'ROLL_OUT',dblclick:'DOUBLE_CLICK',mousedown:'MOUSE_DOWN',mousemove:'MOUSE_MOVE',mouseout:'MOUSE_OUT',mouseover:'MOUSE_OVER',mouseup:'MOUSE_UP',mousewheel:'MOUSE_WHEEL'};
// check if the event exists in the list
if(events[EventStr] && MouseEvent[events[EventStr]]){
cSelector.addEventListener(MouseEvent[events[EventStr]],func1);
}
}else if(typeof(EventStr) == 'object'){
// add the event
cSelector.addEventListener(EventStr,func1);
}
return I;
}
public static function remove()
{
cSelector.parent.removeChild(cSelector);
return I;
}
}
}
Here you go, some steps in the right direction. However, this is a really, really, really crappy idea.
//$.as
package
{
import flash.display.DisplayObject;
//NOTE: there's NO class definition
public function $( selector : DisplayObject ) : IDisplayObject
{
//traverse displaylist to find <code>selector</code>
//and return an instance of IDisplayObject that holds the reference
}
}
//IDisplayObject.as
package
{
public interface IDisplayObject{
function alpha( value : Number ) : IBinding;
}
}
//IBinding.as
package jquery
{
public interface IBinding{
function bind( eventName : String, callback : Function, ...parameters ):void;
}
}
Once you've created concrete implementations of these you can do:
$( someMC ).alpha( .5 ).bind( 'click', function(){ trace( 'what a miraculously crappy idea !!!!' ) } );
You could try it like this:
interface Test {
function doBla(): Test
function moreBla(): Test
}
public class StaticTest {
private static const instance: Test = new InternalTest()
public static doBla() : Test {
return instance.doBla();
}
public static moreBla() : Test {
return instance.moreBla();
}
}
internal class InternalTest implements Test {
function doBla(): Test {
trace("bla");
return this;
}
function moreBla(): Test {
trace("more bla");
return this;
}
}

Referencing own constructor in inner function

Here's a toy example distilled from a complex class:
public class MyClass {
public function MyClass() {
trace('Created');
}
public static function makeObjectAsync(callback:Function):void {
inner();
function inner():void {
var object:MyClass = new MyClass(); // line 10
callback(object);
}
}
}
After calling the static function:
MyClass.makeObjectAsync(function(object:Myclass):void { ... })
the following run-time exception occurs at line 10:
TypeError: Error #1007: Instantiation attempted on a non-constructor.
Why is this, and what can I do about it?
Edit
It appears that new (MyClass)() works. Now I'm possibly more confused.
Not too clear on the WHY to be honnest. It has to do with the scope inherited by anonymous functions, depending on how they are declared.
I have 2 solutions for you though.
If your makeObject method was not static, it would work.
Declare your anonymous function the other way :
public static function makeObjectAsync(callback:Function):void {
var inner : Function = function():void {
var object:MyClass = new MyClass();
callback(object);
};
inner();
}
You shouldn't call your variable "object". Why do you nested your inner function? Why don't you just:
public static function makeObjectAsync(callback:Function):void {
callback(new MyClass());
}
Or if you really want that nested function:
public static function makeObjectAsync(callback:Function):void {
inner();
function inner():void {
callback(new MyClass());
}
}
And you can't recall the class' constructor again, use a function which is called in the constructor then call it again. With this you aren't referencing the constructor but creating a new instance of the class.

What is the best way to implement a singleton pattern class in Actionscript 3?

Since AS3 does not allow private constructors, it seems the only way to construct a singleton and guarantee the constructor isn't explicitly created via "new" is to pass a single parameter and check it.
I've heard two recommendations, one is to check the caller and ensure it's the static getInstance(), and the other is to have a private/internal class in the same package namespace.
The private object passed on the constructor seems preferable but it does not look like you can have a private class in the same package. Is this true? And more importantly is it the best way to implement a singleton?
A slight adaptation of enobrev's answer is to have instance as a getter. Some would say this is more elegant. Also, enobrev's answer won't enforce a Singleton if you call the constructor before calling getInstance. This may not be perfect, but I have tested this and it works. (There is definitely another good way to do this in the book "Advanced ActionScrpt3 with Design Patterns" too).
package {
public class Singleton {
private static var _instance:Singleton;
public function Singleton(enforcer:SingletonEnforcer) {
if( !enforcer)
{
throw new Error( "Singleton and can only be accessed through Singleton.getInstance()" );
}
}
public static function get instance():Singleton
{
if(!Singleton._instance)
{
Singleton._instance = new Singleton(new SingletonEnforcer());
}
return Singleton._instance;
}
}
}
class SingletonEnforcer{}
I've been using this for some time, which I believe I originally got from wikipedia of all places.
package {
public final class Singleton {
private static var instance:Singleton = new Singleton();
public function Singleton() {
if( Singleton.instance ) {
throw new Error( "Singleton and can only be accessed through Singleton.getInstance()" );
}
}
public static function getInstance():Singleton {
return Singleton.instance;
}
}
}
Here's an interesting summary of the problem, which leads to a similar solution.
You can get a private class like so:
package some.pack
{
public class Foo
{
public Foo(f : CheckFoo)
{
if (f == null) throw new Exception(...);
}
}
static private inst : Foo;
static public getInstance() : Foo
{
if (inst == null)
inst = new Foo(new CheckFoo());
return inst;
}
}
class CheckFoo
{
}
The pattern which is used by Cairngorm (which may not be the best) is to throw a runtime exception in the constructor if the constructor is being called a second time. For Example:
public class Foo {
private static var instance : Foo;
public Foo() {
if( instance != null ) {
throw new Exception ("Singleton constructor called");
}
instance = this;
}
public static getInstance() : Foo {
if( instance == null ) {
instance = new Foo();
}
return instance;
}
}