我一直试图让“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/