I am making a mini state manager library for objects (because. don't ask.) and I want to use an approach like this (pseudo-code)
states = {}
when object is initialized {
if object.keys.states {
states[object.name] = object.keys.states;
}
}
/*
When object is initialized:
if object.keys.states exists:
states[object.name] = object.keys.states
*/
Is there a way to achieve this in typecript/javascript
is this typescript? if this is typescript you could use a class and an interface to execute that code or a constructor inside a class
class states {
states: State[] = [];
constructor(statesc?: State[])
{
if (statesc) {
for(var state in statesc)
{
//no need to do objects keys if you can rotate trough the given parameter
//btw only a class constructor can be called when an object is instantiated otherwise you need to do the
//logic after it has been created
this.states.push(statesc[state]);
}
}
}
}
interface State{
id: number;
name: string;
}
//then you can do this
let states = new States(states); and the constructor gets called
Related
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();
I'm building an angular application and I have a class that I'm defining within another ts file. I'm trying to get a property that is defined by the constructor but I'm within an object that is in another object. Normally I would use the "this" keyword but it is referring to the object I am in and not the parent class.
here is the use of the class:
var devList = new DateList(dates)
here is a simplified version of the DateList class:
export class DateList {
date
constructor(input){
this.date = input
}
devs = {
bluegreen: {
dates: this.date.bluegreen //<-----------I believe "this" in this
// case refers to bluegreen,
// how do I get it to refer
// to this instance of the
// DateList class?
}
}
}
EDIT
I'm a beginner to programing so I don't understand what a function has to do with an object, inside of another object. can anyone explain how to fix the issue, and how the issue applies to functions?
Setting class attributes happens before the constructor, so this.date is undefined when you are declaring the class attribute 'devs'. Move setting 'devs' inside the constructor and it will work:
export class DateList {
private date: any;
public devs: Object;
constructor(input: Object){
this.date = input
this.devs = {
bluegreen: {
dates: this.date.bluegreen
}
}
}
}
let dateList: DateList = new DateList({
bluegreen: 'bluegreen_val'
});
console.log(dateList.devs);
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.
I have a situation where I need to define a static property on a class in Kotlin and when its compiled to Javascript have it become a true static field on that class. In this situation companion objects do not work.
For example, if I have an abstract class and its implementing class like below:
abstract class MyAbstractClass{
abstract val id: Int
}
class MyClass: MyAbstractClass(){
override val id: Int = 1 //I want this to actually be "static" on the MyClass
}
The Javascript that this compiles down to is this:
function MyAbstractClass() {
}
function MyClass() {
MyAbstractClass.call(this);
this.id_jz5fma$_0 = 1;
}
Object.defineProperty(MyClass.prototype, 'id', {
get: function () {
return this.id_jz5fma$_0;
}
});
But what I need it to compile down to is this:
function MyAbstractClass() {
}
function MyClass() {
MyAbstractClass.call(this);
}
MyClass.id = 1;
So that the id field does actually statically exist on MyClass without having to make a new instance of MyClass.
I've tried using a companion object but that creates a separate object/function called MyClass$Companion and then assigns the id field to that and never actually assigns it statically to MyClass.
How can I go about setting true static fields like this in Kotlin?
Right now we don’t have a direct way to do it, so I’ve created issue https://youtrack.jetbrains.com/issue/KT-18891
As a workaround, you can write a function like that:
inline fun <reified T : Any> addStaticMembersTo(source: Any) {
val c = T::class.js.asDynamic()
val ownNames = js("Object").getOwnPropertyNames(source) as Array<String>
val protoNames = js("Object").getOwnPropertyNames(source.asDynamic().constructor.prototype) as Array<String>
for (name in ownNames + protoNames) {
c[name] = source.asDynamic()[name]
}
}
And use like:
class A {
companion object {
init {
addStaticMembersTo<A>(object {
val bar = 1
fun foo() {}
})
}
}
}
or even make companion object's members available as a static member of class:
class B {
companion object {
val bar = 1
fun foo() {}
// should be at the end of companion object
init {
addStaticMembersTo<B>(this)
}
}
}
The full example available here:
https://try.kotl.in/#/UserProjects/uube1qikg3vsegtnefo0ad0jag/30f1qf87dt5k5vjhciirt4t108
I'm have method a that decorates a given array of objects:
class Vehicle {
static fromArray(vals) {
return vals.map((v) => { return new Vehicle(v); });
}
}
...I would like to extend that to work on a series of child-classes:
class Boat extends Vehicle {
}
class Car extends Vehicle {
}
Car.fromArray([{name: 'volvo'}]) // should return Car objects, not Vehicle
What do I replace Vehicle with in the parent? Or do I have to override fromArray in the child objects?
You could slightly modify your code:
'use strict'
class Vehicle {
static fromArray(vals) {
var constr = this; // <-- don't need this if you use an arrow function below
return vals.map(function(v) { return new constr(v); });
}
}
class Boat extends Vehicle {
}
class Car extends Vehicle {
drive() { console.log('driving'); }
}
var base = Vehicle.fromArray([1])[0];
var car = Car.fromArray([1])[0];
car.drive();
//base.drive(); // <-- will throw exception
The key here is that for static methods, the this variable is set to the type itself, so you can new this() to create an object of the same type.
Note: this is tested on Chrome (V8), so should work on Node / iojs, BUT, I'm not 100% sure this is according to spec.
In static methods, the this context is typically the constructor function itself, so you can just use that instead of referring to your Vehicle explicitly:
class Vehicle {
static fromArray(vals) {
return vals.map(v => new this(v));
}
}
Notice that static methods are not bound, so if you reference them as a callback or so you have to care about getting this right.