html canvas shenanigansのボタンオブジェクトをプログラムしようとしています。その後、私は次のように定義して、これらのオブジェクトの1を生産しています"for(element in window)"を使用して変数をjavaScriptに変更しようとしています:なぜそれは未定義になりますか?
gameFont = "Calibri"; // Default button font
fontSize = 12; // Default button font size in px
fontColour = "white"; // Default button font colour
function ui_button(options) {
var that = {};
that.context = options.context;
that.hpos = options.hpos;
that.vpos = options.vpos;
that.width = options.width;
that.height = options.height;
that.radius = options.radius;
that.txt = options.txt;
that.fontColour = options.fontColour;
that.fontSize = options.fontSize;
that.font = options.font;
// Check if any of our keys weren't specified.
for (i=0;i<Object.keys(that).length;i++) {
// If the value is empty
if (!Object.values(that)[i]) {
// Then search the ENTIRE window for variables
for (element in window) {
// If the current element shares a name with the key we tested
if (element == Object.keys(that)[i]) {
// Replace this object's value with the global one
alert("Changing "+Object.keys(that)[i]+" with value of "+Object.values(that)[i]+" into "+eval(element));
alert(eval(element));
var ttt = eval(element)[0];
alert("ttt:"+ttt);
Object.values(that)[i] = ttt;
alert(Object.values(that)[i]);
alert("Internal var "+Object.keys(that)[i]+" now has value of "+Object.values(that)[i]+" from "+eval(element));
}
}
}
}
/* blahblah, more function stuff for the object */
return that
}
:
but_endTurn = ui_button({
context: ctx,
hpos: 50,
vpos: 50,
width: 80,
height: 30,
radius: 5,
txt: "End Turn"
});
私はこれを行うと、機能は同じことをここに私は後に説明します私のコードは、あります定義されていないすべての変数の処理:ここでは例としてfontColour
を使用しましょう。
fontColour
が未定義であることを認識すると、ウィンドウ内の要素を調べて、fontColourという名前の変数を探します。
それが見つかりました。
alert(eval(element));
これは正しく私に"white"
の値を与えます。
次に、私はそれの外に変数を作る:
var ttt = eval(element)[0];
alert("ttt:"+ttt);
また、これは正しくデバッグ警告で"white"
を述べています。
これまでのところ良いです。その後、私はttt
として変数を定義します(私はevalの(要素としてまっすぐそれを定義するときにも同じことが起こる)[0])
Object.values(that)[i] = ttt;
alert(Object.values(that)[i]);
alert("Internal var "+Object.keys(that)[i]+" now has value of "+Object.values(that)[i]+" from "+eval(element));
が、常に警戒戻りObject.values(that)[i]
ため"undefined"
! 2番目のアラートの他の変数は常に正しく表示されます。
これがなぜ、そして/または、ソリューションを提供しているのかを誰にでも教えてもらえますか?
ありがとうございます。
私はあなたがevalのを削除し、私はそれであったオブジェクトに私のグローバル値を格納し、提案どおりに私のコードを変更しました。問題を修正しました。ご助力ありがとうございます。 – Kalavinka