Doubt about the creation of an object

Asked

Viewed 78 times

1

I’m new to this world of Javascript programming and I still have a lot of difficulties with things that are, to my mind, relatively simple but that I still can’t solve. I intend to create a function that shows multiple objects in an HTML5 canvas inside the CC. I have several . png in my library with names like: a1, a2, A3..., A13, B1, B2... etc. I randomly choose 3 or 4 of these objects to show on canvas. However, I don’t know how to make the link between the name of the variable I pass to my function and the object to create on canvas.

The variable drawing passed as parameter is a string with the name of the objects a1, a2, etc. But when creating the new variable cards I cannot put the name of the variable where I have italics. There it accepts the name of objects directly but I don’t know how to connect to a variable I pass as parameter.

function Desenhar(**desenho**) {
   var cards = new lib.*desenho*();
   this.addChild(cards);
}   

Can someone help me?

How? : ) There are several functions, some I haven’t finished, mainly drawing. The code is an implementation of the game Blackjack. I have buttons to make calls from the main functions. Apparently the game itself works. Hand out the cards, check the numbers, make the sums and say who won, lost or was eliminated. I have a simple interface made in Animate with the buttons. Now I wanted to draw the game as it happens. I may have code errors and I’m sure I have them, but now I’ve hit the drawing problem. If it was an object only I could drag it to the canvas and show it whenever I wanted, but the cards are chosen randomly and are many cards. The cardVal passed as parameter I always take the names of the cards, a1, a2, etc...

1 answer

2

It is possible to access properties and methods by name (such as string) using square brackets instead of the dot. You can do so:

function Desenhar(tipoDesenho) {
   var cards = new lib[tipoDesenho]();
   this.addChild(cards);
} 
  • It was just a minor change... function showCard(cardVal, whichHand) { 
// nova carta
 
 var newCard = Array();
 
 if (newCard!="") {
 newCard=null;
 }
 
 eval("newCard = new lib."+cardVal+"()");
 self.addChild(newCard);
 newCard.push = cardVal;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.