Creating simple constructor in Javascript - javascript

I am trying to write a constructor that when increment is called it outputs this:
var increment = new Increment();
alert(increment); // 1
alert(increment); // 2
alert(increment + increment); // 7
I am trying to go this way:
var increment = 0;
function Increment(increment){
increment += 1;
};
But the alerts outputs [object object].
Any idea?
EDIT: apparently I am not allowed to touch the existing code, as the cuestion of this exercise is: «Create a constructor whose instances will return the incremented number»

Ususally, you need a method for incrementing the value and you need to call it.
function Increment(value) {
this.value = value || 0;
this.inc = function () { return ++this.value; };
}
var incrementor = new Increment;
console.log(incrementor.inc()); // 1
console.log(incrementor.inc()); // 2
console.log(incrementor.inc() + incrementor.inc()); // 7
But you could take a constructor and implement a toString function for getting a primitive value.
This solution is not advisable, but it works for educational use. (It does not work with console.log here, because it need an expecting environment for a primitive value.)
function Increment(value) {
value = value || 0;
this.toString = function () { return ++value; };
}
var increment = new Increment;
alert(increment); // 1
alert(increment); // 2
console.log(increment + increment); // 7

There are few things that are conceptually wrong here, to keep it simple what you could do is:
function Increment(){
this.value = 0;
}
Increment.prototype.increase = function(){this.value++}
Increment.prototype.getValue = function(){return this.value}
let incrementInstance = new Increment();
incrementInstance.increase();
console.log(incrementInstance.getValue())
Basically what you need to do is to create an instance of Increment and then change the value for it

function Increment(initial){
this.value = initial
}
Increment.prototype = {
constructor: Increment,
inc: function(){
return ++this.value;
}
}
increment = new Increment(0);
alert(increment.inc() + increment.inc());

Related

How to use a variable

I have a question / problem about a variable.
I have two page, in the first one I recover data and in the second one I do some operations.
ActivityPage.js (the first one)
recoverActivity() {
// this function check every second if the size of array > 1000
// this call only a function in the other page (Operations)
Operations.write({
arrayTimestamp: this.arrayTimestamp,
// other things
});
}
//this function when the user click a stop button.
stopActivity() {
Actions.Operations({
arrayTimestamp: this.arrayTimestamp,
});
}
And the I have another page
Operations.js:
//this is called from the first page directly
write(objectData) {
//...
this.timestampCheck(objectData.arrayTimestamp);
//...
}
//this is call from the ComponentDidMount of the second page.
stopClick() {
//...
this.timestampCheck(this.props.arrayTimestamp);
//...
}
Now my problem is in this timestampCheck function:
timestampCheck(timestamp) {
var int_max = 65536;
this.base = 0;
var diff = "";
var start = parseInt(this.contatore);
for (let i = 0; i < timestamp.length; i++) {
let timestamp = parseInt(timestamp[i]);
diff = (this.base + timestamp) - start;
if (diffDestro < 0) {
this.base+= int_max;
diff += this.base;
}
this.tempoReale.push(diff);
}
}
This function is called from the two function stopClick and write and there I have a variable this.base. Now I don't want that this variable loose his value when it leaves the functions timestampCheck. For example the arrayTimestamp has a size > 1000 an so it call the write() functions. here calculations are made and the value of this.base is set.
At this point, if the user clicks the stop key, the stopClick () function is called which calls the same timestampCheck function and must resume the previous value of this.base and not start from scratch.
How do you think I can do it?
thank you so much.
Just use a variable outside of the function to store the new value.
So outside of the function:
var countingValue = 0;
function timestampCheck(timestamp) {
var int_max = 65536;
this.base = 0;
var valueToUse = countingValue > 0 ? countingValue : this.base;
var diff = 0;
var start = parseInt(this.contatore);
for (let i = 0; i < timestamp.length; i++) {
let timestamp = parseInt(timestamp[i]);
diff = (valueToUse + timestamp) - start;
if (diffDestro < 0) {
valueToUse += int_max;
diff += valueToUse;
}
this.tempoReale.push(diff);
countingValue = countingValue + diff;
}
}
So what I have done here is create a variable outside of the function named countingValue with an initial value of 0.
Then underneath the initialisation of this.base I have used a type of If statement known as a ternary operator which says if the current countingValue is more than 0 then we will store that value in a variable named valueToUse otherwise we will use the this.base value and store it in the valueToUse variable.
In the rest of the code I have used the valueToUse variable for the computations now instead of this.base.
Note: I changed your variable diff to an integer because it was a string. You may want to review this and swap a couple of variables around if it's not exactly what you want.

addOne takes in a number as a parameter // and returns that numbers +1?

Function addOne returns undefined result...
const t = 5;
const b = 8;
function addOne () {
add (t + b);
return addOne;}
Pls help to get a sum of 5 + 8 with this function.
const t = 5;
const b = 8;
function addOne () {
return t+b;
}
console.log(addOne()); //13
I am not sure what you are asking, since your method's name is not matching with your implementation. But here are some code that might help you:
const t = 5;
const s = 8; // Note that I have renamed the parameter's name
function addOne () {
return s + 1;
}
function addOneToParameter(x) {
return x + 1;
}
function addTwoConstants () {
return t + s;
}
function addTwoParameters (a, b) {
return a + b;
}
console.log(addOne()); // 9 (The constant 's' + 1)
console.log(addTwoConstants()); // 13 (The constant 's' + constant 't')
console.log(addTwoParameters(1,2)); // 3 (The first parameter + the second parameter)
console.log(addOneToParameter(4)); // 5 (The parameter + 1)
In your original question, you don't need to use a function to perform an addition of two integers. In other words, simply use '+' as operand. Furthermore, pay attention how to return a value from your function.

I don’t understant where that `value` come from, and what that `set` is

The task is:
Modify the code of makeCounter() so that the counter can also decrease and set the number.
I don’t understant where that value come from, and what that set is.
function makeCounter() {
let count = 0;
function counter() {
return count++
}
// Here is this `value`. I understand what it does. But what is it,
// and where did it come from. How can I use it in general?
counter.set = value => count = value;
counter.decrease = () => count--;
return counter;
}
let counter = makeCounter();
alert(counter()); // 0
alert(counter()); // 1
// Also here, what kind of `set` is this?
// I’ve seen one in `Map.prototype.set()`, but there is no `Map` here.
counter.set(10); // set the new count
alert(counter()); // 10
counter.decrease(); // decrease the count by 1
alert(counter()); // 10 (instead of 11)
Source of the code.
Well, this is an arrow function and value is the name of the first parameter of that function.
counter.set = value => count = value;
counter.decrease = () => {
count--;
return counter;
}
The code above translates into this in ES5 syntax:
counter.set = function (value) {
return count = value;
};
counter.decrease = function () {
count--;
return counter;
};

How does implicit passing of object reference work?

I have some Javascript code which works fine so far but I do not understand the how the variable "me" is set in the function "run"?
GameLoop.prototype.run = function() {
this.startTime = new Date().getTime();
var currentTimeMillis = this.startTime;
var loops;
var interpolation=0.0;
this.running=true;
return function(me){
loops = 0;
while (new Date().getTime() > currentTimeMillis && loops < me.MAX_FRAMESKIP) {
me.updateGame();
currentTimeMillis += me.SKIP_TICKS;
loops++;
}
interpolation = parseFloat(new Date().getTime() + me.SKIP_TICKS - currentTimeMillis) / parseFloat(me.SKIP_TICKS);
me.drawGame(interpolation);
}
}
The function is called continuously by the browser's animate function below. Since I do not pass any reference to the call f.run(), i guess the correct reference to me is set implicitly. Can someone explain me or give me some useful links which explains this behaviour?
GameLoop.prototype.recursiveAnim = function() {
var f = this.run();
f.run();
this.animFrame( this.recursiveAnim );
};
By calling run you get a function in return, that function has one parameter and its called me.
For example
var x = function () { return function (me) { return me; } }
// by calling x, you get the function: `function (me) { return me; }
var f = x();
console.log(f(1)); // answer is 1

jQuery - setInterval issue

I am using jQuery to generate and add a random amount of Clouds to the Header of the page and move them left on the specified interval. Everything is working fine, execpt the interval only runs once for each Cloud and not again. Here is my code:
if(enableClouds) {
var cloudCount = Math.floor(Math.random() * 11); // Random Number between 1 & 10
for(cnt = 0; cnt < cloudCount; cnt++) {
var cloudNumber = Math.floor(Math.random() * 4);
var headerHeight = $('header').height() / 2;
var cloudLeft = Math.floor(Math.random() * docWidth);
var cloudTop = 0;
var thisHeight = 0;
var cloudType = "one";
if(cloudNumber == 2) {
cloudType = "two";
}else if(cloudNumber == 3) {
cloudType = "three";
}
$('header').append('<div id="cloud' + cnt + '" class="cloud ' + cloudType + '"></div>');
thisHeight = $('#cloud' + cnt).height();
headerHeight -= thisHeight;
cloudTop = Math.floor(Math.random() * headerHeight);
$('#cloud' + cnt).css({
'left' : cloudLeft,
'top' : cloudTop
});
setInterval(moveCloud(cnt), 100);
}
function moveCloud(cloud) {
var thisLeft = $('#cloud' + cloud).css('left');
alert(thisLeft);
}
}
Any help is appreciated!
This is the way to go:
setInterval((function(i){
return function(){
moveCloud(i);
};
})(cnt), 100);
Engineer gave you the code you need. Here's what's happening.
The setInterval function takes a Function object and an interval. A Function object is simply an object that you can call, like so:
/* Create it */
var func = function() { /* ... blah ... */};
/* Call it */
var returnVal = func(parameters)
The object here is func. If you call it, what you get back is the return value.
So, in your code:
setInterval(moveCloud(cnt), 100);
you're feeding setInterval the return value of the call moveCloud(cnt), instead of the the function object moveCloud. So that bit is broken.
An incorrect implementation would be:
for(cnt = 0; cnt < cloudCount; cnt++) {
/* ... other stuff ... */
var interval = setInterval(function() {
moveCloud(cnt);
}, 100);
}
Now, you're feeding it a function object, which is correct. When this function object is called, it's going to call moveCloud. The problem here is the cnt.
What you create here is a closure. You capture a reference to the variable cnt. When the function object that you passed to setInterval is called, it sees the reference to cnt and tries to resolve it. When it does this, it gets to the variable that you iterated over, looks at its value and discovers that it is equal to cloudCount. Problem is, does not map on to a Cloud that you created (you have clouds 0 to (cloudCount -1)), so at best, nothing happens, at worst, you get an error.
The right way to go is:
setInterval((function(i){
return function(){
moveCloud(i);
};
})(cnt), 100);
This uses an 'immediate function' that returns a function. You create a function:
function(i){
return function(){
moveCloud(i);
};
}
that returns another function (let's call it outer) which, when called with a value i, calls moveCloud with that value.
Then, we immediately call outer with our value cnt. What this gives us is a function which, when called, calls moveCloud with whatever the value of cnt is at this point in time. This is exactly what we want!
And that's why we do it that way.

Categories

Resources