JavaScript initialize an object using complex reference [duplicate] - javascript

This question already has answers here:
Self-references in object literals / initializers
(30 answers)
Closed 7 years ago.
var ok = {
makeScreens: function () {
this.screens = {
x: 2,
y: this.x * 10;
};
}
}
I want to initialize the this.screens variable, but I can't refer to x when I'm initializing y . Can someone tell me, how to refer to the this.screens.x?
Thank you very much.

You can't. You'll have to do it in two steps:
var ok = {
makeScreens: function () {
this.screens = {
x: 2
};
this.screens.y = this.screens.x * 10;
}
}

Another thing you could do is use a constructor:
var ok = {
makeScreens: function() {
this.screens = new (function(){
this.x = 2;
this.y = this.x * 10;
})();
}
}

Related

Can't read property 'push' of undefined when I'm using setInterval (javascript) [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?
(4 answers)
Closed 1 year ago.
I have a constructor where I define a ListFactory and a function called Start, I don't know why if I'm not using a setInterval it works:
constructor(w = 800, h = 400) {
super("imgs/bg.png", 0, 0, w, h, -5, 0);
this.bird = new Bird();
this.pipes = new ListFactory();
this.score = 0;
}
start() {
this.randomNumber=Math.floor(Math.random() * 250);
window.addEventListener('keydown', event=> {
this.bird.incrementHop();
});
this.pipes.push(new PipeC(150 + this.randomNumber));
}
But if I use a setInterval it doesn't work and it prints a "Cannot read property 'push' of undefined" error
constructor(w = 800, h = 400) {
super("imgs/bg.png", 0, 0, w, h, -5, 0);
this.bird = new Bird();
this.pipes = new ListFactory();
this.score = 0;
}
start() {
this.randomNumber=Math.floor(Math.random() * 250);
window.addEventListener('keydown', event=> {
this.bird.incrementHop();
});
setInterval (function () {
return this.pipes.push(new PipeC(150 + this.randomNumber));
}, 2000);
}

"this" accessed inside an array of another object's "this" - javascript [duplicate]

This question already has answers here:
How do I correctly clone a JavaScript object?
(81 answers)
Closed 4 years ago.
Consider this example:
If you were to take the above code and run it, the console message would be 100. Why does it print out 100 when I added the 100 to the position in obj2's "this"? How do I make it so that obj2 has its own unique "this"? Also please know that is an simplified example of my code, I cannot just make a seperate object in obj2 which contains everything.
var obj1 = function() {
this.obj2Arr = [];
this.pos = {
"x": 0,
"y": 0
};
this.obj2Arr.push(new obj2(this.pos));
console.log(this.pos.x);
// Prints out 100 even though obj2 was where I added the 100 for it's "this".
// Why does it do that, and how do I make obj2's "this" unique to it?
};
var obj2 = function(pos) {
this.pos = pos;
this.pos.x = this.pos.x + 100;
};
var example = new obj1();
console.log(example);
This is because pos is an object and objects are always passed by reference in javascript.
To answer your question: use Object.assign to create a fresh object:
var obj1 = function() {
this.obj2Arr = [];
this.pos = {
"x": 0,
"y": 0
};
this.obj2Arr.push(new obj2(Object.assign({}, this.pos)));
console.log(this.pos.x);
};
var obj2 = function(pos) {
this.pos = pos;
this.pos.x = this.pos.x + 100;
};
var example = new obj1();
console.log(example);

Arrow function not working but anonymous function does? [duplicate]

This question already has answers here:
Official information on `arguments` in ES6 Arrow functions?
(2 answers)
Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?
(4 answers)
Closed 5 years ago.
I have the following code
function coroutine(g) {
var it = g();
return () => it.next.apply(it, arguments);
// also tried () => { return it.next.apply(it, arguments);
}
var run = coroutine(function* () {
var x = 1 + (yield);
var y = 1 + (yield);
yield (x + y);
});
And the following testing has been executed.
run()
{value: undefined, done: false}
run(10)
{value: undefined, done: false}
run(30).value
"1function* () { var x = 1 + (yield); var y = 1 + (yield); yield (x + y);}1function* () { var x = 1 + (yield); var y = 1 + (yield); yield (x + y);}"
However, shouldn't the last run(30).value returns the value of 42?
However, it works after I change the arrow function to old anonymous function?
function coroutine(g) {
var it = g();
return function() { return it.next.apply(it, arguments) };
}

Javascript setInterval time not working [duplicate]

This question already has answers here:
Changing the interval of SetInterval while it's running
(17 answers)
Closed 5 years ago.
I can't seem to figure out why the farmerTime is not updating when you level up. There is a button that just adds a level to farmingLevel.
window.setInterval(function() {
farmerTime = 2500;
farmerLevel = 3;
x = farmerTime;
y = farmerLevel;
z = x / y;
farmerTime = z;
if (farmers >= 1) {
a = farmers;
b = potatoes;
c = a * 1;
d = b + c;
potatoes = d;
}
}, farmerTime);`
You need to define farmerTime before you use it. In your case, before the setInterval function. Also, if you want to change the farmerLevel you need to change it somewhere else, not in the setinterval function.
Changing level example:
<button type="button" onclick="setFarmerLevel(farmerLevel + 1);">Change level </button>
And the code for the interval thing:
var farmerTime = 2500;
var farmerLevel = 1;
var setFarmerLevel = function (level) {
farmerLevel = !level ? 1 : level;
farmerTime = farmerTime / farmerLevel;
clearInterval(farmerInterval);
farmerInterval = window.setInterval(run, farmerTime);
};
var run = function () {
if (farmers >= 1) {
a = farmers;
b = potatoes;
c = a * 1;
d = b + c;
potatoes = d;
}
};
var farmerInterval = window.setInterval(run, farmerTime);
UPDATE
I forgot setInterval's function time cannot be change in runtime, so the code is updated now.

this.state is undefined when used in function React JS component [duplicate]

This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 6 years ago.
I have the React component below and I want to access this.state.board (a 2D array with 0 or 1 for each element) from a function randomPosition(). When I call randomPosition it returns "cannot read property state of undefined". Am I doing something wrong with the this keyword?
var App = React.createClass({
getInitialState(){
return {
board: []
}
},
randomPosition: function(){
//generates a random position on this.state.board array
var position = [];
var positionX = null;
var positionY = null;
var generatePosition = function(){
positionX = Math.floor(Math.random() * 64);
positionY = Math.floor(Math.random() * 64);
if(this.state.board[positionX][positionY] === 1){
position.push(positionX, positionY);
return position;
} else {
generatePosition();
}
}
generatePosition();
}
})
thanks for the help!
Your generatePosition function will have its own scope and hence this inside this function will point to its own scope rather than the outer scope where state is accessible. You can store the reference of the outer scope and then use that inside this function like
randomPosition: function(){
//generates a random position on this.state.board array
var position = [];
var positionX = null;
var positionY = null;
var that = this;
var generatePosition = function(){
positionX = Math.floor(Math.random() * 64);
positionY = Math.floor(Math.random() * 64);
if(that.state.board[positionX][positionY] === 1){
position.push(positionX, positionY);
return position;
} else {
generatePosition();
}
}

Categories

Resources