Is it possible to call a function at the second an object is being called?
I have following object:
var z;
var a = {
b: function(){
return z * 2;
}
c: function(){
return z * 3;
}
d: function(){
return z * 4;
},
e: function(){
return z * 5;
}
}
var onObjectInvoke = function(){
z = (new Date()).getTime();
}
I want to reset the value of z before a.d() is being called, here's the flow I mean, when a.d() is called:
call onObjectInvoke.
call a.d();
I'm looking for some kind of constructor, is there any way?
Why can't you just call onObjectInvoke() before calling a.d()? Your life will be a lot easier if you allow your functions to be stateless and operate on given parameters rather than using a global z variable.
var z;
var a = {
d: function(x){
return x * 4;
}
}
var onObjectInvoke = function(){
return (new Date()).getTime();
}
z = a.d(onObjectInvoke());
var z;
var a = {
b: 2,
c: 3,
d: function(){
onObjectInvoke();
return z * 4;
}
}
var onObjectInvoke = function() {
z = (new Date()).getTime();
}
console.log(a.d());
One simple way is to add one more layer and then access onObjectInvoke() in that layer first and return the functions from that layer as object and call the desired function on return value
a.defaultFunc().d()
var z;
var a = {
defaultFunc: function() {
onObjectInvoke()
return {
b: function() {
return z * 2;
},
c: function() {
return z * 3;
},
d: function() {
return z * 4;
},
e: function() {
return z * 5;
}
}
}
}
var onObjectInvoke = function() {
console.log('reseting z')
z = (new Date()).getTime();
}
console.log(a.defaultFunc().d())
console.log(a.defaultFunc().e())
In such a case you most certainly don't want to use z directly but invoke a function that returns the value for you. And in that function, you will either reset z or return it depending on your current use case.
Having external code that heavily modifies the behavior/outcome of a function is always a bad idea with regard to maintainability and readability.
var z;
var resetZ = true;
var a = {
getZ: function() {
if (resetZ) {
z = (new Date()).getTime();
}
return z;
},
b: function() {
return this.getZ() * 2;
}
c: function() {
return this.getZ() * 3;
}
d: function() {
return this.getZ() * 4;
},
e: function() {
return this.getZ() * 5;
}
}
a.d()
You for sure should not use a global resetZ, but as it is not clear how exactly you use your code it is not clear how to structure the code. Or maybe getZ should be a free function, instead of a function belonging to the object.
Related
class A {
constructor(inval){
this.c = inval;
}
b() {
return this.c + 1;
}
e(z) {
return z+ Math.floor(Math.random()*10);
}
d() {
let x = {
x1: this.b(),
x2: this.e(this.b()),
}
return x;
}
}
var inst = new A(5);
var instret = inst.d();
console.log(instret);
Question: in method d() statement "let x" is it possible to use the x1 property as a argument to x2:this.e() call like this:
let x = {
x1: this.b(),
x2: this.e(x1),
}
tried several combinations none worked. Basically is there a better way than to repeatedly type "this.b()" as parameter to this.e() when what I clearly want as parameter is x1 ?
Set key2 as a function and use this to access another key from the same object.
var obj = {
key1: 5,
key2: function() {
return this.key1 + 10;
}
};
alert(obj.key2()); // 15
You can use IIFE or what #Adeel recommended
class A {
constructor(inval) {
this.c = inval;
}
b() {
return this.c + 1;
}
e(z) {
return z + Math.floor(Math.random() * 10);
}
d() {
let x = ((x1) => ({
x1,
x2: this.e(x1),
}))(this.b());
return x;
}
}
var inst = new A(5);
var instret = inst.d();
console.log(instret);
I'm having trouble with this JavaScript exercise. I'm given a function that defines three different variable/value pairs and within that function are multiple nested IIFEs that change those same values. The goal of the exercise is to change the variable's values to a certain value. So here is the code that I was presented:
var scopeExercise = function() {
var a = 1,
b = 2,
c = 3;
result = "a: " + a + ", b: " + b + ", c: " + c;
(function firstFunction() {
var b = 5,
c = 6;
(function secondFunction() {
var b = 8;
(function thirdFunction() {
var a = 7,
c = 9;
(function fourthFunction() {
var a = 1,
c = 8;
})();
})();
})();
})();
return result;
};
console.log(scopeExercise());
And they want the var a = 1, b = 8, and c = 6. I'm still having trouble understanding the function scope because I've tried commenting out the thirdFunction and fourthFunction so that they don't get called before the outer functions and it still won't change the values of var a, b, and c. Also, I don't understand why the nested functions aren't getting executed since they should be immediately invoked.
try this:
var scopeExercise = function () {
var a = 1, b = 2, c = 3;
(function firstFunction() {
b = 5;
c = 6;
console.log('firstFunction()');
(function secondFunction() {
b = 8;
console.log('secondFunction()');
(function thirdFunction() {
a = 7;
c = 8;
console.log('thirdFunction()');
(function fourthFunction() {
a = 1,
c = 6;
console.log('fourthFunction()');
})();
})();
})();
})();
result = "a: " + a + ", b: " + b + ", c: " + c;
return result;
}
console.log(scopeExercise());
added the prints that you will see that all functions were executed
I have the following json object
{
....
....
data: function() {
var x = 10;
function isBig() {
return x>6;
}
return x;
}
}
I want the isBig to be a function inside data.
When I call data.isBig I am getting undefined and data.isBig() gives me an error saying isBig is not a function.
First of all, that is not JSON. It is an object.
The way your object is structured currently, isBig is only accessible from inside data. If you want to access it outside data, the simplest way is to make it a property of the outer object:
{
data: function()
{
var x = 10;
return x;
}
isBig: function(x)
{
return x > 6;
}
}
If you don't want to do that, then an alternative would be this:
{
data: function()
{
var x = 10;
this.isBig = function(x)
{
return x > 6;
}
return x;
}
}
Calling data() works normally (returns 10), whereas calling new data() returns an object with a property isBig which corresponds to the function. This allows you to do this:
new myObj.data().isBig()
obj = {
data: function(){
var x = 10;
return this.isBig(x);
},
isBig: function(x){
return x > 6;
}
};
And if you want to reproduce the function but useally your better off with an contructor add that point.
f = {
isSmall: function(){},
isBig: function(x){
return x > 6;
}
};
obj = {
data: function(){
var x = 10;
return this.isBig(x);
},
isBig: f.isBig
};
obj.data();
obj.isBig(2);
f.isBig(2);
update
solution works in foreach loop but not in for loop
function x(number){
return number - 10;
}
var i = 0
var runtimefunctions = {};
var allLevels = {"1":"State","2":"Educational_Services","3":"Principal_Networks","4":"Schools"}
for (var key in allLevels) {
runtimefunctions[i] = function() { return x(i); };
i++;
};
console.log(runtimefunctions[1]()); // -6
console.log(runtimefunctions[2]()); // -6
console.log(runtimefunctions[3]()); // -6
tried hard to make functions but it's first time to create such thing so cant understand the proper way...
I have a function..
function x(number){
return number - 10;
}
runtimefunctions = {};
now I have a loop to run
[1,2,3].forEach(function(y){
//here I want to create a function.. which will make a function x(y) -- like this
runtimefunctions[x] = new Function("return function x_" + levelIterator + "(levelIterator){ console.log(levelIterator); x(" + y + ") }")();
});
so basically..want to make functions like this.
runtimefunctions= {
"1": x(1),
"2": x(2),
and so on
}
Is this what you need?
function x(number){
return number - 10;
}
var runtimefunctions = {};
[1,2,3].forEach(function(y){
runtimefunctions[y] = function() { return x(y); };
});
console.log(runtimefunctions[1]()); // -9
console.log(runtimefunctions[2]()); // -8
console.log(runtimefunctions[3]()); // -7
To satisfy your next (for-in) requirement, you need to closure the index variable with additional function call:
var runtimefunctions = {}, i = 0;
var allLevels = {"1":"State","2":"Educational_Services","3":"Principal_Networks","4":"Schools"}
for (var key in allLevels) {
runtimefunctions[i] = function(index){ return function() { return x(index); } }(i++);
};
It is much easier.
For example:
const createFunctionWith = (x) => {
return (param) => console.log(x, param)
}
let a = [1,2,3].map(x => createFunctionWith(x));
console.log(a[1]("bebe")); // 2, "bebe"
https://jsfiddle.net/muLxoxLd/
You could do something like this
// Found in your code
var x = (a) => {
console.log(a)
};
var runtimefunctions = {};
[1, 2, 3].forEach(function(y) {
//Create a function with a parameter named "levelIterator"
runtimefunctions[y] = Function("levelIterator", "{ console.log(levelIterator); x(" + y + ") }");
});
runtimefunctions[1]('test')
I come across singleton pattern, it's quite tricky to understand how to implement it, and I know some people would suggest to avoid it most of the time, so below is specific singleton variation that I find it easy to understand, but somehow I feel that this is not the best implementation of this pattern, can you guys suggest better form of this pattern.
var Foo = (function () {
var instance;
var _priVar = 2;
var log = function() {
console.log("Hello");
};
function Singleton(x, y) {
if (instance) {
return instance;
}
this.name = x;
this.age = y + _priVar;
this.log = log;
instance = this;
}
Singleton.getInstance = function () {
return instance || new Singleton();
}
return Singleton;
}());
and my goal is that when we do following
var a = new Foo("Bob", 24);
var b = new Foo();
var c = Foo();
var d = Foo.getInstance();
we will still get
a == b // true
a == c // true
a == d // true
a.name // 'Bob'
b.age // 26
c.log // 'Hello'
d.name // 'Bob'
The simplest singleton, also known as module pattern, consists of an object literal:
var foo = (function () {
var x = "Bob",
y = 24,
_priVar = 2;
function log() {
console.log("Hello");
}
return {
name: x,
age: y + _priVar,
log: log
};
}());
If you want to introduce lazy initialisation, you can use an extra getInstance function like in your implementation:
var getFoo = (function () {
var instance = null;
return function getFooInstance() {
if (instance) return instance;
var x = "Bob",
y = 24,
_priVar = 2;
function log() {
console.log("Hello");
}
return instance = {
name: x,
age: y + _priVar,
log: log
};
};
}());
A singleton should never use a constructor like in your code, that's just unnecessary. If you feel a need to pass arguments for initialisation, don't make it a singleton.