<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)