【JavaScript高级程序设计】12、函数表达式(2)----私有变量

1、严格来讲,JavaScript中没有私有成员的概念;所有对象属性都是公有的。任何在函数中定义的变量都可以认为是私有变量,因为不能再函数的外部访问这些变量

 

<!DOCTYPE html>
<html>
    <head>
        <title>Privileged Method Example 2</title>
    </head>
    <body>
        <script type="text/javascript">
        
            (
                function()
                {
                    var name = "";
                    num = 0;
                    
                    Person = function(value)
                    {                
                        name = value;
                        ++num;
                    };
                    
                    Person.prototype.getName = function()
                    {
                        alert("the num is:" + num);
                        return name;
                    };
                    
                    Person.prototype.setName = function (value)
                    {
                        name = value;
                    };
                }
            )();
            
            var person1 = new Person("Nicholas");
            alert(person1.getName());   //"Nicholas"
            person1.setName("Greg");
            alert(person1.getName());   //"Greg"
                               
            var person2 = new Person("Michael");
            alert(person1.getName());   //"Michael"
            alert(person2.getName());   //"Michael"

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

结果:

 

posted @ 2016-07-22 09:47  cutter_point  阅读(83)  评论(0)    收藏  举报