Creating an instance of a class to call static methods - javascript

I recently came across some code which looks something like this,
class MyClass {
private static instance: MyClass;
private myString: string;
public static Instance(myString) {
if (!this.instance) {
this.instance = new this(myString);
}
return this.instance;
}
private constructor(myString: string) {
this.myString = myString;
}
public getMyString() {
console.log(this.myString);
}
}
My question is, what is the need to do something like this? Why would a person create an instance like this, instead of creating an instance of the class 'the normal way'.
What is the benefit of doing thing like this?

It looks like the Singleton pattern. This pattern is used to ensure that a class has only one instance: the constructor is private, so it cannot be used from the outside of the class.
Regarding this particular implementation, I would suggest a couple of fixes:
this.instance in the static method should be MyClass.instance instead
in the following call new this(myString), myString will be undefined because non static variables cannot be referenced from the static context
there is no way to set myString
public static Instance { ... } should be a static method instead: public static instance() { ... }

Related

Invoking private method from static method ES6

I am unable to call private or non static method from static method in class, below is the example
class a {
fun1(){
console.log('fun1');
}
static staticfun(){
console.log('staticfun');
this.fun1();
}
}
a.staticfun();
I am trying to expose only staticfun method which internally calls all private methods, but this gives me this.fun1 is not a function. I tried to find many ways to find it with 'this', but it does work.
How do I call private instance methods inside static methods?
fun1 is not a static function, so you need to define a new instance of the a class in order to call it:
class a {
fun1() {
console.log('fun1');
}
static staticfun() {
console.log('staticfun');
new this().fun1();
}
}
a.staticfun();
You should note that this is not good practice, though. You shouldn't have a static method relying on non-static logic.
A workaround would be to pass an instance of a to the static function, but that completely defies the point of having a static method in the first place.
Another way is to call the function directly from the class prototype (meaning literally the prototype property, not __proto__), if you want to avoid instantiating it.
class a {
fun1(){
console.log('fun1');
}
static staticfun(){
console.log('staticfun');
this.prototype.fun1();
}
}
a.staticfun();
First, read this SO question
It's possible, You can create an instance of class a and then invoke from the instance the method fun1.
Although, There is no sense to call a non-static method from a static one.
static means that this method belong to the object (not to the instance)
class a {
fun1(){
console.log('fun1');
}
static staticfun(){
console.log('staticfun');
const classInstance = new a()
classInstance.fun1();
}
}
a.staticfun();

Is it possible to pass a jQuery object as a constructor parameter to a typescript object?

We are trying to figure out a peculiar behaviour of typescript. In the following two code examples, a jQuery object should be altered by typescript. In the example that works fine, we reference the jQuery object by using the selector engine in a method after our typescript class is instantiated. This works:
namespace Company.Module {
export class GenericService {
private statefulObject: JQuery;
public constructor( ) {
}
private _toggleObjectState(): void {
this._statefulObject.toggleClass('text-hide text-success');
}
public SetObjectState(): void {
this.statefulObject = $('#statefulObject');
_toggleObjectState();
}
}
}
Whereas passing the jQuery object in the constructor does not work:
namespace Company.Module {
export class GenericService {
private statefulObject: JQuery;
public constructor( _statefulObject: JQuery ) {
this.statefulObject = _statefulObject;
}
private _toggleObjectState(): void {
this._statefulObject.toggleClass('text-hide text-success');
}
public SetObjectState(): void {
_toggleObjectState();
}
}
}
We would like to understand why this is the case.
Unfortunately this was a non-issue. Our code did not work because we were referencing an object that was added to the DOM dynamically. When passed to the typescript constructor, the object simply was not loaded in the DOM, therefore it could not be manipulated. Moderators please feel free to remove this question.

TypeScript: use private or public in constructor

I'm new to TypeScript world, and I've seen examples with this to deal with injected objects and set it to a property of the component (this.anything)
First with public and setting by hand to this.nav
export class XPTO {
constructor(public nav: NavController) {
this.nav = nav;
}
}
and this, with private
export class XPTO {
constructor(private nav: NavController) {
//this.nav is nav?
}
}
in both cases after construct the object this.nav is a NavController object.
What are the differences of both implementations? Or this is the same when compiled to plain javascript?
Actually in your first example the explicit assignment is not needed at all:
export class XPTO {
constructor(public nav: NavController) {
// This line is not required.
// this.nav = nav;
this.someFunction();
}
someFunction(){
console.log(this.nav); // Prints out the NavController.
}
}
Whenever you specify public or private on a constructor parameter a corresponding public/private variable is created on the class and filled with the value of the parameter.
So really, the only difference of the two code samples is that one is private and the other one is public.
The resulting JavaScript will be the same. However, the compiler will throw an error, if you are trying to access private variables in your code.
public and private, as a lot of Typescript features, are only TypeScript modifiers. I'm not sure the compiler names these variables exactly the same, but from a JavaScript point of view, the code will be essentially the same.
The interest of Typescript is to give you features like type checking, it doesn't necessarily always modifies the outputted code.

$http.post and TypeScript accessors

I am writing an AngularJS app (v1.3.15) using TypeScript 1.5 in Visual Studio 2013. I have run across a problem with TypeScript object properties/accessors and JSON serialization using $http.post(). My AngularJS is pretty solid I think but I am quite new to TypeScript.
My TypeScript class looks like this:
module Wizard.Models {
import Address = Wizard.Models.Address;
"use strict";
export class YourDetailsModel {
public useSecondaryAsPrimary: boolean;
private _primaryFirstName: string;
private _primaryLastName: string;
private _primaryAddressModel: Address = new Models.Address();
get primaryFirstName(): string {
return !this.useSecondaryAsPrimary ? this._primaryFirstName : this.SecondaryFirstName;
}
set primaryFirstName(primaryFirstName: string) {
this._primaryFirstName = primaryFirstName;
}
get primaryLastName(): string {
return !this.useSecondaryAsPrimary ? this._primaryLastName : this.SecondaryLastName;
}
set primaryLastName(primaryLastName: string) {
this._primaryLastName = primaryLastName;
}
get primaryAddressModel(): Address {
return !this.useSecondaryAsPrimary ? this._primaryAddressModel : this.SecondaryAddressModel;
}
set primaryAddressModel(primaryAddressModel: Address) {
this._primaryAddressModel = primaryAddressModel;
}
public SecondaryFirstName: string;
public SecondaryLastName: string;
public SecondaryAddressModel: Address = new Models.Address();
}
}
My intention is that when the object is serialized, all the public members and properties via accessors should be serialized, and the private properties should not. The current behaviour is that some of the private members are being serialized whereas some of the public members are not.
Is this asking too much? There are other ways for me to achieve this so it's not the end of the world if I can't get it working. I don't actually need to fiddle with the model class in this way.
But it's the most elegant way of keeping the model playing its cards close to its chest, so to speak.
Any help appreciated. M.
Is this asking too much? There are other ways for me to achieve this so it's not the end of the world if I can't get it working. I don't actually need to fiddle with the model class in this way
There is no runtime difference between a private and a public member. That is to say that the JavaScript emitted for each is exactly the same.
I suggest using a variable naming convention on top of private/public e.g. public foo and private _foo. Then during serialization you can check if a property name starts with _.

Qt programming: How to use custom data type in QVariantMap?

I am writing a Qt app that maps a C++ class to Javascript object in QtWebkit. Firstly let me explain what I am trying to do:
I have a class inherited from QObject:
class myobj : public QObject {
Q_OBJECT
public:
myobj();
~myobj();
pulbic slots:
void getData();
}
And in another class I tried to add myobj instances to QVariantMap:
QVariantMap anotherClass::getObj() {
myobj* obj1 = new myobj();
myobj* obj2 = new myobj();
QVariantMap items;
items.insert(QString("0"), QVariant(*obj1));
items.insert(QString("1"), QVariant(*obj2));
return items;
}
And then I got the following error:
error: no matching function for call to ‘QVariant::QVariant(myobj&)’
So I tried to add declarations:
Q_DECLARE_METATYPE(myobj);
But I got:
error: ‘QObject::QObject(const QObject&)’ is private
Any idea about this?
Like the compiler said, no constructor of QVariant exists that take a myobj as parameter. Have you tried to use the qVariantFromValue function instead?
I think this is what you are searching for.
If you register your custom type with Q_DECLARE_METATYPE(myobj), your class needs a public default constuctor (ok), a public destructor (ok) and a public copy constructor (MISSING which the error message is telling you), see the documentation.

Categories