JavaScript: variable within an object is not defined - javascript

I'm having problems when trying to store a 2D-array in an object variable.
var prTClass = {
prT: Create2DArray(5,8),
setPriceT: function(i,j,price){
prT[i][j] = price;
},
...
}
Create2DArray() is not throwing any error, and the code is this:
function Create2DArray(rows,columns) {
var mat = [];
for(var x = 0; x < rows; x++){
mat[x] = [];
for(var y = 0; y < columns; y++){
mat[x][y] = 'X';
}
}
return mat;
}
The message error I'm getting is "Uncaught ReferenceError: prT is not defined".
I also tried to instantiate the variable with an init() function, like this:
prT: [],
init: function(){
this.prT=Create2DArray(5,8);
},
What's the problem? Thank you.

You're lacking this. You can never access prT as just prT. You must always access it as either this.prT from within the context of that object, or prTClass.prT from outside.

Related

Javascript ternary condition operator not working as expected

I'm making a Row class for a block game I'm creating. I currently have this code for the class:
function Row(size, rowNum, state) {
this.size = size;
this.rowNum = rowNum;
this.cells = state ? this.fromState(state) : this.empty();
}
Row.prototype.empty = function () {
var cells = [];
for (var x = 0; x < this.size; x++) {
cells.push(null);
}
return cells;
};
Row.prototype.fromState = function (state) {
var cells = [];
for (var x = 0; x < this.size; x++) {
var tile = state[this.rowNum][x];
cells.push(tile ? new Tile(tile.position, tile.value) : null);
}
return cells;
};
I got 'position is undefined' error in tile.js. I found this was because the variable tile was null (and so tile.position was undefined). But then, I realized I already had the ternary operator, which, supposedly, already knows that tile is null then pushes null instead of pushing new Tile(tile.position, tile.value). It appears that the ternary operator is not working as expected.
Why is this happening and how do I fix it?
Edit: For clarity: this is my constructor for Tile:
function Tile(position, value) {
this.x = position.x; // This is the line where I am getting the error
this.y = position.y;
this.value = value;
this.previousPosition = null;
this.mergedFrom = null;
}
And the actual error:
TypeError: position is undefined

array changing values for a strange reason

Given the code below:
function createJson() {
var varry = new Array();
varry = x;
for (i=0 ; i < arry.length ; i++) {
if (arry[i]["questionVisibility"] == "1"){
if (arry[i]["questionType"] != 3) {
varry[i][1] = document.getElementById('te'+arry[i]["id"]+'et').value;
} else {
e = document.getElementsByName("te"+arry[i]["id"]+"et")[0];
p = e.options[e.selectedIndex];
varry[i][1] = p.text;
}
}
}
console.log(x);
console.log(varry);
Where X is an array that has been created like this(inside a different function):
x = document.getElementById("jsonData").value;
x = JSON.parse(x);
x = x[0];
x = x.data;
x = JSON.parse(x);
Can anyone explain me why when i call the createJson() function, the x array is changed? (x is already created when the createJson() is called)
Thanks in advance!
it's because of line
varry = x;
assigning an array to variable creates kind of reference of original value so when you modify varry it also modifies x
if you want to get a copy of x into varry without reference use
array.slice() like this:
varry = x.slice();
this will insert values from x into varry without creating 'reference' to original array

Javascript - see if object contains function, if so, return it

I have a function which takes in a String. The function checks if the object in the list has this function(functionName). If it contains that function, how can I return it? Obviously, return list[i].message would work, but thats not what im after. I want do use the parameter functionName in this case.
function message(){
return "hello";
}
function test(functionName);
listLength = list.length;
for(i = 0; i < listLength; i++){
if(list[i].hasOwnProperty(functionName}{
return (?)
}
}
var x = test("message");
alert(x);
Grateful for response
the comment from Pointy is right, but you have to consider that having a function detached by its owner will screw the scope, so you will no longer have access to the right this object
var test = {
number: 0,
testFunction: function() {
return this.number;
}
}
console.log(test.testFunction()); // output: 0
var x = test.testFunction;
console.log(x()); // output: undefined
maybe you should use
var y = test.testFunction.bind(test);
console.log(y()); // output: 0

scriptProcessorNode.onaudioprocess not able to access global variables

I am building class around a scriptProcessorNode oscillator. I have wrapped my onaudioprocess event handler in a function Gendy.prototype.process. I can access global variables and functions from within this wrapper function, but they are not accessible from within the onaudioprocess function.
I devised a work around for the properties, to redefine them in the wrapper function, but this doesn't work when trying to call another method, a random walk method, with this.walk().
Here is my code:
Gendy.prototype.process = function(){
var point = 0;
var index = 0;
var y = 0;
var breakpoint = this.breakpoint;
var freq = this.freq;
var walk = this.walk();
this.scriptNode.onaudioprocess = function(audioProcessingEvent){
var outputBuffer = audioProcessingEvent.outputBuffer;
var outputData = outputBuffer.getChannelData(0);
for(var j = 0; j < outputData.length;j++){
// linearly interpolate between the new breakpoint positions
// get the interp point by comparing index to the x distance
var lerp = (index - breakpoint[point].x) / (breakpoint[point+1].x - breakpoint[point].x);
y = lerp * (breakpoint[point+1].y - breakpoint[point].y) + breakpoint[point].y;
if(point < breakpoint.length && index >= breakpoint[point+1].x) {
point++;
}
outputData[j] = y;
index+=freq;
if(index >= breakpoint[breakpoint.length-1].x){
index = 0;
point = 0;
walk();
}
}
}
}
This makes sound, but returns the errors:
Uncaught TypeError: walk is not a function
for few lines and then
Uncaught TypeError: undefined is not a function
forever.
Is this a bug with the scriptProcessorNode? Any insight would be appreciated!
no bug in scriptProcessorNode, the issue is the below line:
this.scriptNode.onaudioprocess = function(audioProcessingEvent){
the this varible inside the onaudioprocess would refer to this.scriptNode object by default, you can handle it in one of two ways:
Use bind( as you have done in your answer):
this.scriptNode.onaudioprocess = function(audioProcessingEvent){
...
}.bind(this)
use a local variable to hold the value of this, and use that local variable in place of this:
var self = this;
this.scriptNode.onaudioprocess = function(audioProcessingEvent){
...
I was able to access this from within the onaudioprocess function by attaching .bind(this) to it.
Here is the code:
Gendy.prototype.process = function(){
this.scriptNode.onaudioprocess = function(audioProcessingEvent){
var outputBuffer = audioProcessingEvent.outputBuffer;
var outputData = outputBuffer.getChannelData(0);
for(var j = 0; j < outputData.length;j++){
// linearly interpolate between the new breakpoint positions
// get the interp point by comparing index to the x distance
var lerp = (this.index - this.breakpoint[this.point].x) / (this.breakpoint[this.point+1].x - this.breakpoint[this.point].x);
this.y = lerp * (this.breakpoint[this.point+1].y - this.breakpoint[this.point].y) + this.breakpoint[this.point].y;
if(this.point < this.breakpoint.length && this.index >= this.breakpoint[this.point+1].x) {
this.point++;
}
outputData[j] = this.y;
this.index+=this.freq;
if(this.index >= this.breakpoint[this.breakpoint.length-1].x){
this.index = 0;
this.point = 0;
this.walk();
}
}
}.bind(this);
}

JAVASCRIPT --> Why do I get the error message "Uncaught TypeError: number is not a function "?

I wonder why I get the error message (Uncaught TypeError: number is not a function) , this is my bit of Code:
<script type = "text/javascript">
function dataparse(points)
{
points = points.substr(0, points.length - 1);
var linar = points.split("\n");
// Break each point by line break
var wrkar = [];
var pntar = [];
for (var i = 0; i < linar.length; i++)
{
wrkar = linar[i].split(",", 2);
// Break each point into x and y
pntar.push(new google.maps.LatLng(parseFloat(wrkar[0]), parseFloat(wrkar[1])));
}
return pntar;
}
var cd = [
(30.40545181622765, -9.582610613708539)
(30.405229737948233, -9.577975756530805)
(30.40300892737293, -9.577546603088422)
(30.402268645956614, -9.584241396789594)
];
var df = dataparse(cd);
alert('df');
(30.40545181622765, -9.582610613708539) evaluates to -9.582610613708539
Together with the next line, it's interpreted as
-9.577975756530805(30.405229737948233, -9.577975756530805)
Which of course fails because -9.577... is not a function.
Your dataparse function expects a string, given points.substr(0,points.length - 1)
you initialize cd as an array, but the parser tries to execute (num1, num2) (num3, num4) as a function (see GGG's answer for the reason).
You're points array isn't valid. You will have to use square brackets for the points itself and split them by commas
var cd = [
[30.40545181622765, -9.582610613708539],
[30.405229737948233, -9.577975756530805],
[30.40300892737293, -9.577546603088422],
[30.402268645956614, -9.584241396789594]
];
And with that you will also have to modify (simplify) your dataparse function to handle the array correctly
function dataparse(points) {
var i,
length,
pntar = [];
for (i = 0, length = points.length; i < length; i++) {
pntar.push(new google.maps.LatLng(points[i][0], points[i][1]));
}
return pntar;
}
You are getting this, because every number in your brackets is evaluated, you should replace that with the proper argument which your function accepts... since you are using substr, but actually you want to pass an array you should add some code to your function as well :
function dataparse(pairs)
{
for ( i=0; i < pairs.length ; i++ ) {
var wrkar = pairs[i].split(", ",2);
var pntar = [] ;
pntar.push( new google.maps.LatLng(parseFloat(wrkar[0]), parseFloat(wrkar[1])) );
return pntar;
}
}
var cd = [
"30.40545181622765, -9.582610613708539",
"30.405229737948233, -9.577975756530805",
"30.40300892737293, -9.577546603088422",
"30.402268645956614, -9.584241396789594"
];
var df = dataparse(cd);
alert('df');​
here is a jsfiddle http://jsfiddle.net/ptQfc/
1st misake:
var cd = [
(30.40545181622765, -9.582610613708539)
(30.405229737948233, -9.577975756530805)
(30.40300892737293, -9.577546603088422)
(30.402268645956614, -9.584241396789594)
];
Javascript array has to be separated with commas and not with newlines!
The error raises because of cd variable. You use parentheses, however it is not corrent.
Following your dataparse method cd variable should look like:
var cd = "30.40545181622765, -9.582610613708539\n"+
"30.405229737948233, -9.577975756530805\n"+
"30.40300892737293, -9.577546603088422\n"+
"30.402268645956614, -9.584241396789594";
UPDATE: However, you can rewrite your code in the more nice form:
function dataparse(points) {
var pntar = [];
for (var i = 0; i < points.length; i++) {
pntar.push(new google.maps.LatLng(points[i][0], points[i][1]));
}
return pntar;
}
var cd = [
[30.40545181622765, -9.582610613708539],
[30.405229737948233, -9.577975756530805],
[30.40300892737293, -9.577546603088422],
[30.402268645956614, -9.584241396789594]
];
var df = dataparse(cd);
alert(df);
You've misunderstood the syntax required and it's causing a whole host of errors, namely trying to interpret your variables as a function.
In Javascript, the var=[val,val2] construct creates an array. You're trying to treat the contents of the brackets as a string, and split it as such.
A better way to store the array would be:
var cd = [
[30.40545181622765, -9.582610613708539],
[30.405229737948233, -9.577975756530805],
[30.40300892737293, -9.577546603088422],
[30.402268645956614, -9.584241396789594]
];
Your function could then be written as:
function dataparse(linar) {
var wrkar = [] ;
var pntar = [] ;
for (var i = 0; i < linar.length; i++) {
wrkar = linar[i]; // Break each point into x and y
pntar.push( new google.maps.LatLng(parseFloat(wrkar[0]),parseFloat(wrkar[1])));
}
return pntar ;
}
as linar is an array of arrays, each time you loop through the array it sets the next array down as the value of wrkar, which gives you the x and y coordinates.

Categories

Resources