javascropt oop与闭包

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>闭包</title>
</head>

<body>
<script>
    // JavaScript Document

//    var Person=function(name,age){
//        this.name=name;
//        this.age=age;
//        this.say=function(){
//            console.info('hello')
//        }
//    }
//    Person.prototype={
//        Person:function(){
//
//        },
//        hello:function(){
//            console.info(this.age+' '+this.name)
//        }
//    }
//    var p=new Person();
//    p.say();
//
//    var p1=new Person('zhangsan',19);
//    p1.hello();


    var Person=function(){
        var id=1;//private
        this.name='';//public
        //闭包访问私有变量
        this.say=function(){
            return function(){
              return id;
            };
        }
    }
    Person.age=19;//静态变量  可以通过类或对象访问
    /**
     * 通过原型扩展属性和方法
     * @type {{}}
     */
    Person.prototype={
        address:'',
        hello:function(){
            console.info('hello');
        }
    }

    //实例化对象
    var person=new Person();
    console.info('类变量:'+Person.age)
    console.info('私有变量:'+person.id);//访问不到 underfined
    console.info('使用闭包访问 私有变量:'+person.say()())
    person.name='张三';
    person.address='重庆';
    console.info(person)
    console.info(new Person().hello())


</script>

</body>
</html>

猜你喜欢

转载自lishdfsdf.iteye.com/blog/2288555