Add variable method to ES6 class [duplicate] - class

This question already has answers here:
ES6 - declare a prototype method on a class with an import statement
(3 answers)
Closed 5 years ago.
With an ES6 Class, you can declare methods as follows:
class Foo {
bar() {}
}
However, I need to import methods from an external file and load them into the class. Something like this:
const barMethod = require('./bar');
class Foo {
bar: barMethod
}
However, this doesn't work. I've looked around a while for the syntax for this and it isn't really mentioned. What is the right way to do this?
Is there a way to extend the Class perhaps? Because the Class is so big, I am breaking it out into several files for organizational purposes, but each method needs to be able to refer to the Class with this.
Mixins perhaps?

A class in ES6 still uses the .prototype so you can extend a class definition after its declaration, by adding methods to the `.prototype.
Original declaration:
class Foo {
bar() {}
}
Add some new methods:
Foo.prototype.newBar = someNewMethod;
Or, in a more modular way, perhaps you want to just pass Foo to each module in it's module constructor and it can just add its methods to Foo.prototype.
Or, each module could just define its own class with its own set of methods (all designed to eventually be Foo methods and then you could use one master function to import all the sub-definitions and copy all the methods from each of the imported classes to your main Foo class prototype to end up with one master class.
Keep in mind that methods are just functions on the prototype object, even when the class is declared with the ES6 class syntax. They can be assigned to other objects with regular Javascript that just operates on properties of an object.

You can .call() barMethod from Foo instance bar property, optionally setting this to this : Foo instance
class Foo {
bar() {
barMethod.call(this)
}
}

Related

Can you use a method reference to define a class implementing a Functional interface in java 8

So we know that Java 8 method references can be used to replace anonymous class creation. I'm curious if there's a way to use them to define named classes that implement a functional interface, something -- vaguely -- along the lines of
public interface Bar {
String returnSomeString();
}
public class Foo implements Bar = someObjectInstance::toString;
I know you can't use equals in defining a class, but something like that...

Mark Haxe Class for forced extend?

Is there a compiler meta for Class declaration, that prevents creating Class instance before extending it? In other words - some sort of opposite of #:final meta.
Like so (last line of code):
class A {
// ...
}
class B extends A {
// ...
}
// ...
var b = new B(); // OK
var a = new A(); // induce compiler-error
Simply don't declare a constructor at all for class A
Both the other answers are correct (no constructor or private constructor), but there are a few more details that you may interest you:
Here's an example of no constructor. Of note is that A simply doesn't have a constructor, and B simply doesn't call super(). Other than that, everything else works as you'd expect.
Here's an example of a private constructor. You still can't instantiate a new A(), but you do still need to call super() from B's constructor.
Technicalities:
Use of some features (like a default value on a member variable) will cause A to get an implicit constructor, automatically. Don't worry, this doesn't affect constructability or whether you need to call super(). But know that it is there, and if necessary an implicit super() call is prepended to B's constructor. See the JS output to verify this.
In any case, know that you can still instantiate an A at runtime with var a = Type.createInstance(A,[]); as compile-time type checks do not limit RTTI.
Related discussion:
Aside from private/no constructor, Haxe doesn't have a formal notion of abstract classes1 (base classes not expected to be instantiated) or abstract methods2 (functions on abstract base classes with no implementation that must be implemented by a derived class.) However, Andy Li wrote a macro for enforcing some of those concepts if you use them. Such a macro can detect violations of these rules and throw compile-time errors.
1. Not to be confused with Haxe abstracts types, which are an entirely different topic.
2. Not to be confused with virtual functions, which wikipedia describes as a function which can be overridden (though various docs for various languages describe this highly loaded term differently.)
One way of achieving this is to create private Class constructor:
class A {
private function new() {
// ...
}
}
// ...
var a = new A(); // Error: Cannot access private constructor

how scala treat companion object?

I'm new to Scala with Java background.
In java when we want to share any field among different objects of class. we declare that field static.
class Car {
static NO_Of_TYRES = 4;
// some implementation.
public int getCarNoOftyres(){
NO_Of_TYRES; // although it's not a good practice to use static without class name
//but we can directly access static member in same class .
}
}
But in Scala we cannot declare static fields in class, we need to use object(companion object) for that.
In scala we will do like this,
class Car {
println(NO_Of_TYRES); // scala doesn't let us do that. gives error
println(Car.NO_Of_TYRES);// this is correct way.
}
object Car {
val NO_Of_TYRES: Int = 4;
}
I'm just curious, how scala treat companion objects?
what different these two key-words (class and object) makes ?
why does scala not letting us access NO_Of_TYRES directly in class?
Companion objects are singleton class instances (and definitions), just to recall singleton in java is more or less:
class Foo {
private Foo() { }
/* boilerplate to prevent cloning */
private static Foo instance = new Foo();
public static Foo getInstance() { return instance; }
public int bar() { return 5; }
}
and then to call method bar of this object:
Foo.getInstance().bar();
Scala removed all this boilerplate and lets you create equivalent thing with just
object Foo {
def bar: Int = 5
}
and to call it you only need
Foo.bar
now what's the difference between 'object' and 'companion object'? It's actually quite simple - companion object (so the object defined in the same file as a class and having the same name) has access to it's related class private fields and methods, and that's probably why scala authors decided that it should reside in the same file - so that references to private fields are in the same file as their declarations (which I think is always the case both in Java and Scala, unless using reflection magic)
I'd like to reference another answer about the same subject: What are the advantages of Scala's companion objects vs static methods?
See also Section 4.3 of Odersky's book Programming in Scala - Chapter 4 - Classes and Objects
Scala treats everything as pure objects with their instances. In this view a java static member is not part of any instance, it lives a separate and different life.
With the tricks of the keyword object and some syntactic sugar, you can achieve the same result but maintaining the stated principle: a single instance of that object is instantiated and a global access point for the instance is provided.
Scala, as you pointed out, cannot have static variables or methods, as known in Java. Instead, there are singleton objects, which are declared with the keyword object. Calling a method in this objects is like calling a static method in Java, except you are calling the method on a singleton object instead.
If this object has the same name of a class or trait, it is called the companion object of the class/trait. A companion object must be defined inside the same source file as the class/trait. A companion object differs from other objects as it has access rights to the related class/trait that other objects do not. In particular it can access methods and fields that are private in the class/trait.
Companion objects provide us with a means to associate functionality with a class without associating it with any instance of that class. They are commonly used to provide additional constructors

base class pointing to inherited class

I have an inherited class which i would like to point to from the base class. Example below
class Base
{
inherited* test;
};
class inherited: Base
{
};
the purpose of this is so that the base class (a character) contains a linked list of the inherited class (items)
ps apologies for any mistakes, i'm new to this site
It might be possible to trick the compiler into accomplishing this, but it's most certainly bad OOP design. If all you want to do is be able to store an instance of the inherited class but can treat it like the base class, then you can simply make inherited* test a base* test and it will accept pointers to either inherited or base (or any other subclass of base).
If you actually want base to treat that instance as inherited, you need to rethink your class hierarchy because you don't actually have an inheritance tree here.

idiomatic way to declare protected method in Scala when allowing for composition?

I have an abstract class in package foo (in this particular case, a trait) that can be implemented by various subclasses, and I'd like to create an orthogonal subclass for use in a more specific package bar that adds package-specific info. It seems the best way is by composition (wrapping) rather than inheritance because otherwise I'd have to declare package-specific versions of every single one of the foo-package subclasses. But this leads to a problem with protected members which need to be forwarded:
package foo {
trait Foo {
protected def bar: Int
}
}
package bar {
import foo.Foo
class Baz
class WrapFoo(wrapped: Foo) extends Baz with Foo {
protected def bar = wrapped.bar
}
}
This leads to an error:
~/test/scala 14:54 152272% scalac testprotected.scala
testprotected.scala:11: error: method bar in trait Foo cannot be accessed in foo.Foo
Access to protected method bar not permitted because
prefix type foo.Foo does not conform to
class WrapFoo in package bar where the access take place
protected def bar = wrapped.bar
^
one error found
Even though WrapFoo is a subclass of Foo, scala doesn't like the call wrapped.bar. I'm guessing this is because the object of type WrapFoo isn't a sub-object of wrapped.
The question is: What's the idiomatic way to declare the protections on bar other than simply making it public? The function bar is meant to be called by other functions in Foo, not publicly. Scala has an expressive protection system but I don't quite understand it. Is this possible at all?
Put both types in a common package, it can be anywhere in the package hierarchy and doesn't have to be an immediate parent.
Then you can use protected[packagename] or private[packagename] to selectively control access.