js 类的声明,方法的扩展



<script type="text/javascript">
//原生的js 的object没有get方法,自己扩展一个 Object.prototype.get
= function(key,defy){ if(this[key]){ return this[key] }else{ if(defy){ return defy } } }
//声明一个类的实例,用类似json的格式。
var person={ name:"haha", age:26 }
/*alert(person['name'])*/ alert(person.name)

//调用自己扩展的get方法
alert(person.get('name')) </script>

在上面的代码中,由于js没有提供get方法,用prototype给Object扩展了个get方法。

 

 

*************************************************************

下面是

function user(){ //相当于 java中的public 
            this.name='xx'; this.age = 12 ; //相当于java 中的private,不能直接通过实例去访问
            var email = "123@qq.com"
            //封装,提供get方法
            this.getEmail = function(){ return email } } var use = new user() alert(use.name) alert(use.getEmail())

有参构造方法:

  function student(name,age,sex){
            this.name = name;
            this.age = age;
            this.sex = sex;
        }
        var aa = new student('bobo',28,'男')
        
        alert(aa.sex)

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM