JavaScript:监听对象属性的改变

<script type="text/javascript">

    var student = {
        name:"李雷",
        age:20
    }


    var age = student.age
    Object.defineProperty( student , "age" ,{
        // 当访问  age 属性值时,就执行该方法
        get:function(){
            console.log("访问  age 的属性值")
            return age
        },
        // 当 student 的age改变时,调用set ()
        set:function( newValue ){

            console.log("新值是:",newValue)
            age = newValue
        }

    })

    // 此时会执行 get() 方法
    console.log("原值:", student.age )

    student.age = 21

    console.log("新值:", student.age )
</script>

原文出处:http://www.malaoshi.top/show_1IX6ZegFsKgd.html