javascript中如何模拟“类”
javascript作为弱类型的放言,没有类似于java,c#中“类”的概念,但实际开发中很多时候会有这样的需求,目前知道有两种方式可以模拟。
1.通过声明一个对象的方式,可有如下代码:
var people = {
age:12,
name:"jack",
sex:"男",
setAge:function(value){
this.age = value;
},
getAge:function(){
return this.age;
},
setName:function(value){
this.name = value;
},
getName:function(){
return this.name;
},
setSex:function(value){
this.sex = value;
},
getSex:function(){
return this.sex;
},
//除了这些属性的读取方法之外还可以有其它方法
sayHi:function(){
document.write("Hi,everybody!");
},
//也可以这样写
function sayHi(){
document.write("Hi,everybody!");
}
}
这样一个“类”就写好了,可以通过如下方式调用:
people.age(或者people.getAge)来获取年龄信息
people.setAge来修改年龄
需要注意的是,由于"people"并不是真正的类,而是javascript的一个对象,所以people中所有元素,无论是属性还是方法,都被javascript当成属性处理,所以全部用","隔开。
2.通过声明一个function的方式
function people(){
var age,name,sex;
this.getAge = function(){
return this.age;
}
this.setAge = function(value){
this.age = value;
}
}
相关操作基本与第一种方法一样。
两种方法的应用场景目前尚不明确,需要进一步学习研究。
-------------------------------
把努力当成习惯
-------------------------------
浙公网安备 33010602011771号