新しい計算機を作る
重要性: 5
3つのメソッドをもつオブジェクトを作るコンストラクタ関数 Calculator
を作りなさい:
read()
はprompt
を使って2つの値を訪ね、オブジェクトプロパティの中でそれを覚えます。sum()
はそれらのプロパティの合計を返します。mul()
はそれらのプロパティの掛け算結果を返します。
例:
let
calculator =
new
Calculator
(
)
;
calculator.
read
(
)
;
alert
(
"Sum="
+
calculator.
sum
(
)
)
;
alert
(
"Mul="
+
calculator.
mul
(
)
)
;
function
Calculator
(
)
{
this
.
read
=
function
(
)
{
this
.
a =
+
prompt
(
'a?'
,
0
)
;
this
.
b =
+
prompt
(
'b?'
,
0
)
;
}
;
this
.
sum
=
function
(
)
{
return
this
.
a +
this
.
b;
}
;
this
.
mul
=
function
(
)
{
return
this
.
a *
this
.
b;
}
;
}
let
calculator =
new
Calculator
(
)
;
calculator.
read
(
)
;
alert
(
"Sum="
+
calculator.
sum
(
)
)
;
alert
(
"Mul="
+
calculator.
mul
(
)
)
;