Javascript面向对象编程(二)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript面向对象编程</title>
</head>
<body>
   <script>

     //函数的闭包
    (function(win) {
        var Person = function(name) {
            var _name = name; //局部变量外部不可访问,模拟私有变量

            if (!Person.prototype.setName) { //保证只执行一次
                Person.prototype.setName = function(name) {
                    _name = name;
                }

                Person.prototype.getName = function(name) {
                    return _name;
                }

                //字面量定义不能用在函数体内
                /*Person.prototype = {
                    constructor: Person, 
                    setName: function(name) {
                        _name = name;
                    },
                    getName: function() {
                        return _name;
                    }
                }*/

            }

        }


        win['Person']= Person;
     })(window)


     var p = new Person('hello');
     p.setName('world');
     alert(p.getName());

   </script> 
</body>
</html>