<!DOCTYPE html>
<html
lang=
"en"
>
<head>
<meta
charset=
"UTF-8"
>
<title>Title
</title>
</head>
<body>
<input
type=
"text"
id=
"userName"
>
<br>
<span
id=
"uName"
></span>
<script>
var
obj
=
{
pwd:
"1234"
};
//主要使用到了get和set方法,最为关键
//Object.defineProperty为对象定义一个新的属性
Object
.
defineProperty
(
obj
,
"userName"
,
{
get:
function
()
{
console
.
log
(
'get init'
);
},
set:
function
(
val
)
{
console
.
log
(
val
);
console
.
log
(
"set init"
);
document
.
getElementById
(
"uName"
).
innerText
=
val
;
}
});
document
.
getElementById
(
"userName"
).
addEventListener
(
"keyup"
,
function
(
event
)
{
console
.
log
(
event
.
target
.
value
);
obj
.
userName
=
event
.
target
.
value
;
})
<
/script>
</body>
</html>