JS 仿java的get set访问器,私有成员, 伪事件

没有什么难度,主要加深对JavaScript的理解


var Student = function (name, no) { var name = name; //相当于私有属性 var no = no; this.setName = function (value) { name = value; for (var i = 0; i < this.nameModifyListeners.length; i++) { this.nameModifyListeners[i](this); } } this.getName = function () { return name; } this.setNo = function (value) { no = value; } this.getNo = function () { return no; } this.sayInfo = function () { alert(name + "," + no); }; /** * function(Student) */ this.nameModifyListeners = []; }

 

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head >
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <script src="Scripts/Student.js" type="text/javascript"></script>
    <script type="text/javascript">
        var stu = new Student("LYX", "2008");
        stu.sayInfo();
        stu.nameModifyListeners.push(onNameChange);
        stu.setName("LYX2");
        function onNameChange(student) {
            alert("student info modified!! name:"+student.getName()+" no:"+student.getNo());
        }
    </script>
</head>
<body>
</body>
</html>

 

posted @ 2012-09-16 00:25  如坐夕阳  Views(776)  Comments(0Edit  收藏  举报