開発環境
- OS X Mavericks - Apple(OS)
- Emacs (CUI)、BBEdit - Bare Bones Software, Inc. (GUI) (Text Editor)
- Safari、Firefox + Firebug (Webプラウザ、プラグイン)
- JavaScript (プログラミング言語)
- jQuery (JavaScript Library)
『初めてのJavaScript 第2版』(シェリー・パワーズ著(Shelley Powers著)、武舎 広幸+武舎 るみ訳、オライリージャパン、2009年、ISBN978-4-87311-425-5) の13章(カスタムオブジェクトと例外の処理)、練習問第13-1、13-2、13-3、13-5.を解いてみる。
その他参考書籍
練習問第13-1、13-2、13-3、13-5.
コード(BBEdit)
Number.prototype.tripler = function () {
return 3 * this.valueOf();
};
var result = '',
i,
f = function (n) {
var a,
i,
max;
if (arguments.length !== 1){
a = [];
for (i = 0, max = arguments.length; i < max; i += 1){
a.push(arguments[i]);
}
throw {
type: 'function f error',
message: '引数の数は1つ: ' + a.join(' ')
}
}
if (typeof n !== 'number'){
throw {
type: 'function f error',
message: '型の引数は数値を指定して下さい。' + n
}
}
return '例外発生無し: f(' + n + ')';
},
Obj = function () {
// データメンバーの隠蔽(varキーワード)
var state = 'on',
background = '#fff';
// こちらのデータメンバーはパブリック
this.changeState = function (){
if (state === 'on'){
state = 'off';
background = '#000';
} else {
state = 'on';
background = '#fff';
}
},
this.getState = function () {
return state;
},
this.getColor = function () {
return background;
};
},
o = new Obj(),
br = $('<br />'),
d0 = $('#d0'),
button = $('<input type="button" />'),
d1 = $('#d1');
result += '1.\n';
for (i = 0; i < 10; i += 1){
result += '(' + i + ').tripler(): ' + (i).tripler() + '\n';
}
for (i = 0.5; i < 10.5; i += 1){
result += '(' + i + ').tripler(): ' + (i).tripler() + '\n';
}
result += '2.\n';
[1, 'a', [1, 2], function (){}, {'a':1, 'b':2}].forEach(function (n){
try{
result += f(n) + '\n';
} catch (e){
result += 'type: ' + e.type + '\n' +
'message: ' + e.message + '\n';
}
});
try{
result += f(1, 2);
} catch (e){
result += 'type: ' + e.type + '\n' +
'message: ' + e.message + '\n';
}
d0.html('');
d0.append('5.').append(br).append(button);
button.val('現在の状態: ' + o.getState() +' クリックで切り替え').
click(function() {
o.changeState();
button.val('現在の状態: ' + o.getState() +' クリックで切り替え');
d1.css('backgroundColor', o.getColor());
});
$('#pre0').text(result);
0 コメント:
コメントを投稿