js类的简单实现与调用
先上一段小代码.里面有注释.
<html>
<script>
function people(name) {
this.name = name;
this.version = 0;
//展示name
this.showName = function() {
alert('my name is ' + this.name);
}
//设置name
this.setName = function(name) {
this.version++;
this.name = name;
}
//获取name
this.getName = function() {
return this.name;
}
}
//这种形式定义的方法不能使用类的属性
people.run = function() {
alert('I can run');
}
//原型方法,可以使用类的属性
people.prototype.showMyName = function() {
if(this.version > 0) str = '我改名字了。现在叫 ' + this.name;
else str = '我的名字叫 ' + this.name;
alert(str);
}
function dog() {
this.name = false;
this.master = false;
this.setName = function(name) {
this.name = name;
}
}
dog.prototype.getName = function() {
return this.name;
}
dog.prototype.setMasterName = function(master) {
this.master = master;
}
dog.prototype.getMasterName = function() {
return this.master;
}
//测试
var p = new people('Jim');
p.showName();
var d = new dog();
d.name = '旺财';
alert(d.getName());
d.setMasterName(p.getName());
alert(d.getMasterName());
alert(d.name + ' 的主人是 : ' + d.master);
alert(d.getName() + ' 的主人是 : ' + d.getMasterName());
</script>
</html>
js里面没有严格的类.只有一层一层的function.理论上有无限层.
js继承
<script>
function base(aa) {
this.aa = aa;
function get_aa() {
return this.aa;
}
}
function sun() {
function show() {
return 'I am sun show';
}
}
sun.prototype=new base('hello world');
alert(sun.get_aa()); //输出 hello world
alert(sun.show()); //输出 I am sun show
</script>