開発環境
- OS X Lion - Apple(OS)
- Safari (Webプラウザ)
- TextWrangler(Text Editor) (BBEditの無料、light版)
- Script言語:JavaScript
- JavaScript Library: jQuery
独習JavaScript 高橋 和也 (著), 竹添 直樹 (著), 里見 知宏 (著) の第7章(オブジェクト指向プログラミング)7.6(スコープと名前空間)練習問題7.6を解いてみる。
その他参考書籍
- JavaScript 第5版 David Flanagan (著), 村上 列 (翻訳)
- JavaScriptクイックリファレンス David Flanagan (著), 木下 哲也 (翻訳), 福龍興業 (翻訳)
グローバルオブジェクトとは、プログラムの全ての場所から参照できるオブジェクトで、JavaScriptプログラムが実行される際に必ず1つのインスタンスが生成される。
2.
コード(TextWrangler)
function ColoredRectangle(height, width, color){
var rgb = getRGB(color);
this.height = height;
this.width = width;
this.color = color;
this.red = rgb[0];
this.green = rgb[1];
this.blue = rgb[2];
function getRGB(color){
return [color.substring(1,3),
color.substring(3,5),
color.substring(5,7)];
}
}
var color = $('#t0').val();
var rect = new ColoredRectangle(10,20,color);
var result = "red: " + rect.red + "<br />" +
"green: " + rect.green + "<br />" +
"blue: " + rect.blue + "<br />";
$('#pre0').html(result);
3.
コード(TextWrangler)
var learnYourself;
if(!learnYourself){
learnYourself = {};
}
learnYourself.ColoredRectangle = function (height, width, color){
var rgb = getRGB(color);
this.height = height;
this.width = width;
this.color = color;
this.red = rgb[0];
this.green = rgb[1];
this.blue = rgb[2];
function getRGB(color){
return [color.substring(1,3),
color.substring(3,5),
color.substring(5,7)];
}
}
var color = $('#t1').val();
var rect = new learnYourself.ColoredRectangle(10,20,color);
var result = "red: " + rect.red + "<br />" +
"green: " + rect.green + "<br />" +
"blue: " + rect.blue + "<br />";
$('#pre1').html(result);
4.
グローバルスコープに別の関数から同じ名前の変数を定義した場合、関数を呼び出した際に変数の値は上書きされる。
コード(TextWrangler)
var result = "";
var a = 'javascript';
function f(){
a = 'perl';
}
result += a + "<br />";
f();
result += a + "<br />";
$('#pre2').html(result);
0 コメント:
コメントを投稿