javascript - 尝试从函数声明全局变量

标签 javascript

我一直试图让“hundredFunction()”在“gameCanvas”变量中输出为100%,其中显示“this.canvas.width = Hundred;”

我需要知道如何将“hundredFunction()”的输出声明为全局变量,以便我的“gameCanvas”变量不会被声明为“未定义”

我希望我的解释是正确的。预先感谢您的帮助。

(注意:我不需要知道它的 jQuery 版本。)

// 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]);        
    }
}

最佳答案

您应该从您的 hundredFunction 返回 100% 并使用此返回的 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]);        
    }
}

此外,您不需要 concat() 函数来实现您正在寻找的内容:

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

关于javascript - 尝试从函数声明全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47010459/

相关文章:

javascript - 如何循环遍历音频对象数组

javascript - 满足条件时停止 Jquery.map

javascript - 对象赋值正在改变值

javascript - 如何使用 Python(最好是 pandas)从 Javascript 表中抓取数据?

javascript - 如何删除 tinyMCE 然后重新添加它?

javascript - fadeout 和 removechild 负载

javascript - 正确实例化复杂的 JS 对象

javascript - 为什么给数组分配一个数字会使数组对象成为 nan?

javascript - reactjs,常量,传递属性

javascript - 编辑 JavaScript 对象