I'm tyring to give a default value to a JavaScript Class.
i.e.
class tr{
constructor(value=null){
this.type = typeof value;
this.val = value;
this.start = new Date();
}
}
Now, if I want to get value I should use something like that:
let trVar = new tr;
console.log(trVar.val);
But I want to call value as default when I call just trVar itself.
I mean:
console.log(trVar);
This should be value.
I don't want to remove type and start.
Thanks.
What you are asking for is an anti pattern to OOP.
When you chose that OOP route, you should use it as intended.
If you'd like to turn an object instance into a single variable simply bind a variable to point to that value you want. or, don't use OOP.
you could create a function that returns only what you want and store whatever you dont want inside it. that would work better for you I guess.
Note:
I am not sure why you'd want to do that but, let trVar = new tr trVal here is the reference to the instance of tr.
Perhaps:
What you are trying to do is get the val field when you instantiate the tr class. Unfortunately the new keyword creates a new instance of which it's reference is stored in trVar... So to only get the value out of the instance you could perhaps do this:
let trVar = (new tr).val;.
Related
I have a Angular service and in it I have variables like this:
export class MyService {
someVariableA = 1;
someParams = {
someVariableB,
otherVariable: this.someVariableA
};
}
and in a component I set the 'someVariableA' to 3
this.myService.someVariableA = 3;
and I want 'otherVariable' to get that value 3 as well, but it doesn't. It remains 1 when I go to get the value.
let v = this.myService.someParams.otherVariable;
Is it possible to set 'otherVariable' this way or any other way via 'someVariableA'?
As #Zulwarnain answered, 1 is a number or a primitive data type. Primitive data types in javascript are passed by value, not by reference which you seem to be expecting here.
An easy fix for this is to assign a function to otherVariable instead. Now just invoke the function someParams.otherVariable() and it will return the value of someVariableA. No need to make this complicated.
export class SingletonService {
public someVariableA = 1;
public someParams = {
otherVariable: () => this.someVariableA
};
}
This is basic javascript with multiple sources covering the subject.
https://codeburst.io/explaining-value-vs-reference-in-javascript-647a975e12a0
I concur with this answer that you will have a better time if you use a reference type like an object/array instead of a primitive value type like a number. By adding one layer of indirection (e.g., someVar = 123 becomes someVar = {value: 123}) you could very easily get similar functionality to what you're seeking.
If, however, your use case requires an object's property to directly act like a reference to a primitive value type stored somewhere else, you can get this behavior by implementing the property as a getter and setter pair. It's more complicated, but it acts the way you want.
Here's an example:
class MyService {
someVariableA = 1;
someParams: {
someVariableB: number;
otherVariable: number;
};
constructor() {
this.someVariableA = 1;
const that = this;
this.someParams = {
someVariableB: 2,
get otherVariable() {
return that.someVariableA
},
set otherVariable(val: number) {
that.someVariableA = val;
}
}
}
}
Note that in order for the otherVariable getter and setter to be able to access the right context, I had to move the code into the constructor and copy this into a new variable I called that. The this context of a getter/setter refers to the object it's a member of, and not some this from an outer scope.
Let's make sure it works:
const ms = new MyService();
ms.someVariableA = 100;
console.log(ms.someParams.otherVariable); // 100
ms.someParams.otherVariable = -5;
console.log(ms.someVariableA); // -5
Looks good; changes to ms.someVariableA are immediately reflected in ms.someParams.otherVariable, and vice versa. All right, hope that helps; good luck!
Playground link to code
You are assigning the value type this will not work like you want. you need to assign reference type
obj ={someVariableA : 1};
someParams = {
otherVariable: this.obj
};
in the above code, if you change the value of obj.someVariableA it will also change the value of someParams.otherVariable
I am expexting that you have knowledge about reference type and value types variables
click here for demo
I don't think you want to do that. I believe you are getting a new instance of the service each time you call it, so the variables get reset.
you might want to set that variable in localStorage instead, and then have the service retrieve it from localStorage. That way it will always be getting whatever it was last set to.
or just pass that variable into your service call, instead of trying to use a local service variable.
Been trying to instantiate an object (called "isSize" below) and assign it to another existing variable (called "sizeObject"), here is the first object ("isSize") within a function:
function Size(isSize) {
this.isSize = 80;
setSize(this.isSize);
}
And here's the second variable of which I want to assign the previous variable to:
var sizeObject;
I've been trying various ways such as the following:
function createSize(isSize){
var isSize = new sizeObject();
}
Anyone got any ideas? Many thanks
If I understand your comment correctly, here is what you are looking for:
// this is the constructor of the `Size` class
function Size() {
this.isSize = 80;
}
function createSize() {
// add this line:
var sizeObject = new Size();
}
It's very hard to understand quite what you're asking, but this:
var sizeObject = new Size(20);
...will create a new object with a isSize property on it with the value 20 if you change Size to:
function Size(initialSize) {
this.isSize = initialSize;
}
(E.g., so it actually uses the argument you give it, rather than using an hardcoded 80.)
Size in the above is a constructor function. You use constructor functions via new.
Which is the best way between:
var myClass = function() {
this.myContainer = function(){ return $(".container");}
this.mySubContainer = function(){ return this.myContainer().find(".sub"); }
}
AND
var myClass = function() {
this.myContainer = $(".container");
this.mySubContainer = this.myContainer.find(".sub");
}
Is there any concrete differences?
The memory problem arose when I have seen that my web page, that has enough javascript ( about 150KB of mine + libs ) takes more then 300-400MB of RAM. I'm trying to find out the problem and I don't know if this could be one of them.
function myClass{
this.myContainer = function(){ return $(".container");}
this.mySubContainer = function(){ return this.myContainer().find(".sub"); }
}
Here you will need to call it something like myClassInstance.myContainer() and that means jquery will search for .container element(s) any time you are using that function. Plus, it will create 2 additional closures any time you will create new instance of your class. And that will take some additional memory.
function myClass{
this.myContainer = $(".container");
this.mySubContainer = this.myContainer.find(".sub");
}
Here you will have myContainer pointing to an object which already contains all links to DOM nodes. jQuery will not search DOM any time you use myClassInstance.myContainer
So, second approach is better if you do not want to slow down your app. But first approach could be usefull if your DOM is frequently modified. But I do not beleave you have it modified so frequently that you may need to use second approach.
If there is a single variable you are trying to assign , then the second approach looks cleaner..
Yes they are different.
MODEL 1:
In the first model, myContainer is a function variable.It does not contain the jQuery object.You cannot call any of jQuery's methods on the objet. To actually get the jQuery object you will have to say
var obj = this.myContainer() or this.myContainer.call()
MODEL 2:
The second model stores the actual jQuery object.
try alerting this.myContainer in both models, u will seee the difference.
Yes this is different. after you fix your syntax error :
function myClass(){... // the parentheses
1st
When you create a new object var obj = new myClass(), you are creating two functions, and the jquery object is not returned until you call it
var container = obj.myContainer();
2nd
As soon as the object is initialized the dom is accessed and you have your objects cached for later use;
var container = obj.myContainer;
I got something for the javascript developers amongst us.
I got the following class:
function MyClass(){
this.__defineSetter__("array", function(val){
alert("setter called");
this._array = val;
});
this.__defineGetter__("array", function(){
alert("getter called");
return this._array;
});
this._array = new Array();
};
Now, what happens is that when I execute
var a = new MyClass();
a.array[0] = "MyString";
alert(a.array[0]);
the getter is called twice (which is fine), but the setter is never executed, as the actual array reference does not change, only the content (I guess expected behavior).
However, I'd also need to be "notified" when the array-content is modified. Thus, the call
a.array[0] = "MyString";
should also cause a setter-call (or something similar, important is to receive a notification when the array content has changed.
Anybody into this? How can this be achieved?
As we know,alert(a.array[0]); will only trigger a.array's getter/setter,and a.array[0] equal var p = a.array; p[0] which means what you want is trigger p[0]'s getter/setter,not just p's getter/setter.
So,we can change our mind to this thinking:
add getter/setter to all items of p
so,we can do it like this:
if some like p[6] = 0 is used , which will trigger p's getter/setter , judge if all item of p has getter/setter .if not add it.
if some like p = [2,3,4] is use , simply first set getter/setter to the value.
and the code is: Jsfiddle
Weird problem here, I'm trying to use a global function to update my settings object, example:
var Settings = new Object;
Settings.savepos = 'true';
function UpdateSetting(obj,value){
eval("Settings.obj = value");
alert(Settings.savepos);
}
The obj is the key of the object, meaning if I call the function with
UpdateSetting('savepos','false')
the alert will always just give me true, how do I convert that eval or any alternative so it will update settings object's key with the value?
You are setting Settings.obj, not setting.savepos.
Try this instead:
function UpdateSetting(obj,value){
Settings[obj] = value;
alert(Settings.savepos);
};
You are always changing the "obj" key of the object to equal value, which is likely to be undefined (or, at least, not defined to what you want) in the context eval() executes it in. So, you have two options. First, you can keep using eval() (although i don't recommend it because it's more pain than necessary):
var Settings = new Object;
Settings.savepos = 'true';
function UpdateSetting(obj,value){
eval("Settings."+obj+" = '"+value+"'");
alert(Settings.savepos);
}
Or, as numerous other have suggested, you can use the array operator[] to access the property by key:
var Settings = new Object;
Settings.savepos = 'true';
function UpdateSetting(obj,value){
Settings[obj] = value;
alert(Settings.savepos);
}
you dont need an eval
you're setting .obj, not .savepos (there is no interpolation for the string)
you may be calling it wrong.
I'm not exactly sure why you don't just set the value directly (eg. Settings.savepos=false;).
You can attach the function to that object to do something similar:
var Settings = new Object;
Settings.savepos = true;
Settings.UpdateSetting = function (prop,value){this[prop] = value;}
Settings.UpdateSetting('savepos',false);
You should be able to use array notation on the object. Underneath it's just a keyed hash.
Try:
Settings[obj] = value;
I'd also suggest passing values as they are, i.e. string, int, etc:
UpdateSetting('key_name', false);