Andrew Lee
Andrew Lee

Reputation: 304

Trying to declare a global variable from a function

I am stuck with trying to get the "hundredFunction()" to output as 100% inside the "gameCanvas" variable where it says "this.canvas.width = hundred;"

I need to know how to declare the output of "hundredFunction()" as a global variable so that my "gameCanvas" variable will not be declared "undefined"

I hope I explained myself correctly. Thank you in advance for any help.

(Note: I do not need to know the jQuery version of this.)

// this loads the function tagged on the <body>
function startGame() {
    gameCanvas.start();
}

// this will allow us to 100% width and height of canvas
function hundredFunction() {
    var n = "100";
    var p = "%";
    var wh = n.concat(p);
    var hundred = wh;
}

var test = hundredFunction();
console.log(test);

// this will declare the variables to create the canvas on the <body>
var gameCanvas = { 
    canvas : document.createElement("canvas"),
    start : function() {
        this.canvas.width = hundred;
        this.canvas.height = hundred;
        this.context = this.canvas.getContext("2d");
        document.body.insertBefore(this.canvas, document.body.childNodes[0]);        
    }
}

Upvotes: 0

Views: 44

Answers (1)

Zenoo
Zenoo

Reputation: 12880

You should return 100% from yourhundredFunction and use this returned var :

function startGame() {
    gameCanvas.start();
}

function hundredFunction() {
    var n = "100";
    var p = "%";
    var wh = n.concat(p);
    return wh; // < Return your value
}

var hundred = hundredFunction(); // < Store it in a variable
console.log(hundred);

var gameCanvas = { 
    canvas : document.createElement("canvas"),
    start : function() {
        this.canvas.width = hundred; // < Use it to your heart's content
        this.canvas.height = hundred;
        this.context = this.canvas.getContext("2d");
        document.body.insertBefore(this.canvas, document.body.childNodes[0]);        
    }
}

Also, you don't need the concat() function to achieve what you're looking for :

function hundredFunction() {
    return '100%'; // < Return your value
}

Upvotes: 2

Related Questions