Why is my array calling everything in it? - javascript

I want the array to call one random variable from it but it calls every variable in it and I don't know why.
Code:
var atk1 = Billy.giveLife("self");
var atk2 = Billy.punch("self");
var attack = [atk1,atk2];
function test(){
var r = Math.round(Math.random()*(attack.length-1));
attack[r];
}
test();

On your first 2 lines you are immediately calling the functions. attack[r] does nothing, square braces are only for selecting an element from an array.
Here’s one solution to what you might be trying to do, using anonymous arrow functions to store your functions to be called later:
var atk1 = () => Billy.giveLife("self");
var atk2 = () => Billy.punch("self");
var attack = [atk1,atk2];
function test(){
var r = Math.round(Math.random()*(attack.length-1));
attack[r]();
}
test();

Okay, I think you are missing braces '()' so I did a little prototype for you, here it is:
http://jsfiddle.net/pvkovalev/e75nx3rn/
I modified your code a little bit to make more visual:
function printf(data) {
$('#out').html($('#out').html() + '<br/>' + data);
}
var atk1 = function() {
printf('atk1');
}
var atk2 = function() {
printf('atk2');
}
var atk3 = function() {
printf('atk3');
}
var atk4 = function() {
printf('atk4');
}
var atk5 = function() {
printf('atk5');
}
var attack = [atk1, atk2, atk3, atk4, atk5];
function test() {
var r = Math.round(Math.random() * (attack.length - 1));
attack[r]();
}
setInterval(function() {
test();
}, 1500)

Related

how to properly call functions in prototype in js

How do I properly call the functions inside pretest?
I get this error: Uncaught TypeError: b.testmenow is not a function
var pretest = function () {
var MAX_NUM = 250.0;
var prebase = function (NEW_NUM) {
this.NEW_NUM = NEW_NUM ? NEW_NUM : true;
};
prebase.prototype.testmenow = function () {
return this.NEW_NUM;
};
return prebase;
};
var b = new pretest(111);
console.log(b.testmenow());
You need to accept your input into new pretest(111) by adding n.
And then you must instantiate your prebase constructor using n.
var pretest = function (n) {
var MAX_NUM = 250.0;
var prebase = function (NEW_NUM) {
this.NEW_NUM = NEW_NUM ? NEW_NUM : true;
};
prebase.prototype.testmenow = function () {
return this.NEW_NUM;
};
return new prebase(n);
};
var b = pretest(111);
console.log(b.testmenow());
It is strange that you have two constructors here, you can surely do this with one.
As Felix has deftly mentioned, you can call pretest(111) instead of new pretest(111).

How to access the value of one variable set from a function from another function

I am making a minecraftpe mod and I have to access the value of something which is set in another (because using setTile in java functions crashes the game as x, y, z are only defined in the useItem template.) So I needed to do this basically here is the function I am using...
var ctx = com.mojang.minecraftpe.MainActivity.currentMainActivity.get();
var seekerProgress = 0;
function newLevel()
{
run: function()
{
try
{
var modWindow = new android.widget.PopupWindow();
var modLayout = new android.widget.LinearLayout(ctx);
var seeker = new android.widget.SeekBar(ctx);
seeker.setProgress(seekerProgress);
seeker.setMax(1);
modLayout.addView(seeker);
modWindow.setContentView(modLayout);
modWindow.setHeight(android.widget.LinearLayout.LayoutParams.WRAP_CONTENT);
modWindow.setWidth(android.widget.LinearLayout.LayoutParams.WRAP_CONTENT);
modWindow.showAtLocation(ctx.getWindow().getDecorView(), android.view.Gravity.CENTER | android.view.Gravity.CENTER, 0, 0);
seeker.setOnSeekBarChangeListener(new android.widget.SeekBar.OnSeekBarChangeListener() {
onStopTrackingTouch: function()
{
seekerProgress = seeker.getProgress();
if (seekerProgress === 1)
{
print(target);
}
}
});
}
}
}
function modFunction()
{
var target = 0; //I want this value to be accessible in the newLevel function
}
What can I do to aide this?

Javascript: Get scoped variable

I'm writing a counter to count an object, and it looks like this:
function myFunc(param) {
this.param = param;
param.foo = function() {
var object = window.JSON.parse(data);
for (i in object) {
counter++;
}
}
}
var foo = new myFunc('data.json');
var counter = 0;
document.write(counter); // displays 0
How can I achieve to get the counter value outside the function? I tried almost everything, from window to return to separate functions.
Any clue?
Update
I prefer a better design like this
function myFunc(param) {
this.param = param;
param.foo = function() {
var object = window.JSON.parse(data);
var counter = 0;
for (i in object) {
counter++;
}
return counter;
}
}
var foo = new myFunc('data.json');
document.write(counter); // displays undefined
Update 2
Sorry, thought it would be easier to have a sample code. But here's the real one: https://gist.github.com/BobWassermann/e709ec303477a015b609
I think you have a couple issues here.
First, you're setting your counter to 0 just before you write. It will always be 0 no matter what you do, even with hoisting.
Second, you never call the foo function, so your counter is never incremented.
Third, param.foo isn't public. I think you want it to be this.foo = function(){ ... }.
Here's a simplified version of the code you posted with my tweaks:
var counter = 0;
var foo;
function myFunc() {
this.foo = function() {
counter = 1000;
}
}
foo = new myFunc();
foo.foo();
document.write(counter);
JSFiddle: http://jsfiddle.net/dgrundel/2ojw2332/2/
Note that JSFiddle doesn't allow document.write, so replaced that part.
function myFunc(param) {
this.param = param;
this.foo = function () {
var object = window.JSON.parse(this.param),
counter = 0,
i;
for (i in object) {
counter++;
}
return counter;
};
}
var foo = new myFunc('{"a":99}');
out(foo.foo());
function out(s) {
document.getElementById('out').innerHTML = '<pre>' + s + '</pre>';
}
<div id="out"></div>
As #Nina Scholz pointed out earlier, I'm retrieving the data asynchron. Javascript started painting the dom before all the values where loaded.
This fixed my problem:
if (document.readyState) {
setTimeout(function() {
var objLen = Object.keys(obj).length;
console.log(objLen);
}, 100);
}
I'm waiting for the document to be ready, then add an additional timeout as buffer.

JavaScript function object methods - getters and setters

I recently started JavaScript and I am having trouble with the classless OOP style it uses. Here is an example of an object I am trying to use:
function block(id, text, distance) {
this.id = id;
this.text = text;
this.distance = distance;
this.getId = function () { return this.id };
this.getText = function () { return this.text };
this.getDistance = function () { return this.distance };
this.addDistance = function (Distance) { this.distance = this.distance + Distance };
}
However this doesn't seem to work. I then did some reading here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects, which seemed to suggest I remove the methods from my function and add them using the prototype object of my block:
block.prototype.getDistance = function () {
return this.distance;
};
block.prototype.addDistance = function (Distance) {
this.distance = this.distance + Distance;
};
But this still doesn't seem to work. For example if I am trying to loop through an array of blocks and add up the distance:
var distTot = 10;
for (var i = 1; i < blocks.length; i++) {
var set = setLarge[i];
distTot = distTot + blocks[i - 1].getDistance;
};
I end up with the following as the contents for the distTot variable: "10function () {\r\n return this.distance;\r\n }function () {\r\n return this.distance;\r\n }"
Could any one please explain to me what I am doing wrong? I have checked to see that they are being instantiated correctly and everything seems fine there. I am pretty sure it is just the methods that are not working correctly.
Thanks in advance!
When you call a function, you should add (), so try getDistance() instead of just getDistance
getDistance is a function so you should call it as a function here
distTot = distTot + blocks[i - 1].getDistance();
otherwise, as you've noticed, you obtain the string representation of the function itself

JS module pattern override function

I have following pattern
BASE = function () {
var that = {};
var number = 10;
that.showNumber = function(){
that.alertNumber();
}
that.alertNumber = function () {
alert(number);
};
return that;
};
CHILD = function () {
var that = Object.create(BASE());
var secondNumber = 20;
// Override base function
that.alertNumber = function () {
alert(secondNumber);
};
return that;
};
var ch = CHILD();
ch.showNumber();
Can you tell me how can I adjust my module pattern inspired by Douglas CrockFord to fully override alerNumber function? So far showNumber function displays 10 instead of 20.
Thank you all in advanced
JSFiddle with code is here
You could change
that.showNumber = function(){
that.alertNumber();
}
to
that.showNumber = function(){
this.alertNumber();
}
But I'm not sure I see why you don't simply use the prototype-base inheritance model.

Categories