js 类的简单实现与调用

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>

 

 

 

 

 

转载于:https://my.oschina.net/u/2338485/blog/692588

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值