Unable to call object properties from functions in JavaScript [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am new to JavaScript and wanted to create a simple game of pong for practice.
I can easily draw the gaming area on the canvas but now there is some problem when I try to draw the bat.
I created a playerBat object with some properties.
var playerBat = {
batWidth:20,
batHeight:100,
x:10,
y:(height/2)-(batHeight/2),
spdY:10
};
Then in the function "drawPlayerBat" I simply drew a rectangle with these properties as parameters.
function drawPlayerBat() {
ctx.fillStyle = "white";
ctx.fillRect(playerBat.x, playerBat.y, playerBat.x+playerBat.batWidth, playerBat.y+playerBat.batHeight);
};
But its not working ! The console says "Unable to get property 'x' of undefined or null reference". Have I made any mistake in syntax or doing this is just not possible ?
Here is the entire code... http://codepen.io/anon/pen/YqgVog?editors=1010
Any help will be appreciated.
Thanks.

Easy fix:
There is really no reason to call
y:(height/2)-(batHeight/2),
since you are defining batHeight two lines above it. It won't behave dynamically - once you set it it won't change when batHeight changes, it will stay the same.
Knowing batHeight value you can simply say that
y:(height/2)-(50),
What answer you probably want:
If the question is about self-referencing in JavaScript, then the answer would be to set the values inside of a function inside of the object and initialize it after declaring it. For example:
var playerBat = {
batWidth: 20,
batHeight: 100,
x: 10,
spdY:10,
init: function(){
this.y = (height/2)-(this.batHeight/2);
return this;
}
}.init();

You need to remove batHeight. Do it like below.
var playerBat = {
batWidth:20,
batHeight:100,
x:10,
y:(height/2)-(100/2),
spdY:10
};

Related

Iterate over array in proxy [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 months ago.
Improve this question
Good day.
I was testing stuff in Javascript with Proxies.
Currently I have this proxy
My question was, how do I iterate over this? I've tried several methods, including object.keys and forEach, which yielded nothing.
Thanks in advance
You need to specify an ownKeys method in the handler you're using to create the proxy or you won't be able to enumerate the keys of the proxy object.
const obj = { test: 'a' };
const handler1 = {
ownKeys(target) {
return Reflect.ownKeys(target);
}
};
const proxy1 = new Proxy(obj, handler1);
console.log(Object.keys(proxy1)) // ['test']
Edit
Actually, you can use Reflect.ownKeys directly also, but you'll want to make sure the behavior is what you expect. For example, it might return length as a key as well.

I was taking a challenge [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I was taking a challenge and one of the questions seems like I got the right answer but it wouldn't pass. Need help understanding why it didn't.
Challenge: Add a method to the Person's prototype called "shoutName" that returns the person's name in all uppercase letters.
function Person(name) {
this.name = name;
this.shoutName = function() {
name.toUpperCase();
return '"' + name.toUpperCase()+'"'
}
}
/* Do not modify the code below this line */
const john = new Person('John');
console.log(john.shoutName(), '<-- should be "JOHN" ');
The question said to add a function to the constructor's prototype.
You didn't do that. You modified the constructor to dynamically add the function to the instance as the instance was created.
Person.prototype.shoutName = function () {
return this.name.toUpperCase();
}
Your function also wrapped the resulting value in quotes, which the question didn't ask you to do.
From your tiny picture, I noticed that your code was:
return '"' + name.toUpperCase() + '"';
Not sure why you added the quotes, just return this.name.toUpperCase(); and it should work fine. You should be referencing this object's property, rather than the input value of just name.
Also, having name.toUpperCase(); on a line by itself does nothing. Unnecessary calculations since that function returns a value that you're not assigning.

Give a second name to a variable in javascript [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
I have a code source that contains a long variable name (postCustomThumbnailsScrollerHeight).
I don't want to rename this variable for the whole code source so that I easily continue the project, but to have a shorthand of its name. I tried following solution (which works) at the first declaration of the variable, but I am not sure if it is the correct way to do so. I have a different color of d in IDE:
var postCustomThumbnailsScrollerHeight= d= $('.post-scroller').outerHeight();
I am seeking by this question your usual expert advice.
No, this isn't really correct: you're not declaring the d variable, only assigning to it, and thus
making it global (which may or not be desired)
making your code incompatible with strict mode
Here's a solution:
var d = $('.post-scroller').outerHeight(),
postCustomThumbnailsScrollerHeight = d;
Note that this should only be done for readability/typing issues, not for downloaded script size: minifiers should be used for that latter goal.
Be also careful that you're not making an alias, but really two variables. If you assign to one, you won't change the other one. It's hard to give a definite advice without more information but the usual solution is to have namespaced object:
Assuming you have a struct
myApp.thumbnailScrollers.postCustom = {height:...
then you would just assign that latter object to a local variable in a module or function:
var s = myApp.thumbnailScrollers.postCustom
In this case, changing s.height would also change myApp.thumbnailScrollers.postCustom.height.
Probably you have different color because in this case b it's global variable.
As for my opinion will be better to write all definitions on different lines:
var postCustomThumbnailsScrollerHeight = $('.post-scroller').outerHeight();
var d = postCustomThumbnailsScrollerHeight;
Although JavaScript doesn't natively support references, you can stimulate them using code such as this:
function d(){
return postCustomThumbnailsScrollerHeight;
}
Then just use d() everywhere. It's not very elegant, but as far as I know it's the only way to get a reference in JavaScript.
Do you have a problem declaring that var in the next line?
You could just do:
var postCustomThumbnailsScrollerHeight = $('.post-scroller').outerHeight();
var d = postCustomThumbnailsScrollerHeight;

The shortest way of using the same event on different Objects [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have several JavaScript Objects (explicit Raphael.js paths), on which I want to apply one event. (e.g.: ".mouseover()")
example:
var p = Raphael(1, 1, 600, 600);
var x = p.path("M100 100 L 300 100") //first raphael.js path
var y = p.path(("M100 200 L 300 200") //second raphael.js path
var z = p.path(("M100 300 L 300 300") //third raphael.js path
var doStuff = function () {
//doStuff
};
x.mouseover(doStuff);
y.mouseover(doStuff);
z.mouseover(doStuff);
Question: Is there a way to shorten this,
so that you need to write .click(doStuff) only once.
JSFiddle example: http://jsfiddle.net/utg3k5mo/
Thank You
Now that you have added a jsFiddle, I know what you're talking about. I previously suggested a method that uses jQuery's .add() function because you tagged your question with jQuery; however, you are using Raphael and not jQuery, so this method didn't work for you. Please change that tag.
The best way to shorten your procedure is creating an array containing the variables and iterate through it:
var array = [x, y, z];
for(var i in array)
array[i].mouseover(doStuff);
Old answer:
jQuery uses .click(). .onClick() doesn't exist.
There are two ways to solve your problem:
First, you could store the event handler in a variable and pass it to the .click() function:
var eventHandler = function() {alert("test");};
x.click(eventHandler);
y.click(eventHandler);
z.click(eventHandler);
Or you could add the variables and invoke .click(function) on the new set:
x.add(y).add(z).click(function() {alert("test");});

Using String/Array String as Variable name in JavaScript? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm coding a game with CraftyJS which uses JavaScript and I ran into problem where I have for loop and I need to use Variable name based on Array String... I have been trying to make it work for few hours now so I'm too tired to explain but please help me if anyone hear this!
So basicly what I'm trying to do is this:
var "TempVar"+Array[i] = Something;
also tried it whitout quotes etc... And by passing it in normal String and then using that but I didn't get it working either. If anyone know how this is supposed to do in JavaScript, or if there is alternative method please let me know that.
Sorry about my bad English, its terribly late and English is not my native language.
Also notice that I'm new to JavaScript so don't hate me too hard...
Basically youre going to need to do this:
//Create an empty object
var myObject = {};
for(var i=0; i<Array.length;i++)
{
//Add properties to the object
myObject["TempVar"+Array[i]] = Something;
}
Create an empty object and then append new properties to it within your loop. JavaScript has this neat little way properties are accessed. You can either use a dot notation like so:
myObject.property = "Blah";
Or you could access the property like an array:
myObject["property"] = "Blah";
Both perform the same operation.

Categories

Resources