<script type="text/javascript">
//1.类的声明
function person(name,age) {
this.name=name;//注意js和Java的区别 Java里name必须先声明,而js里不需要直接this.name就行
this.age=age;
this.f=function () {//注意js中这不是方法里套方法,而是对象里面套对象
// 这种声明方式是把方法声明在了p1对象里面 每生成一个对象 就要加载一个function方法 占用空间
// alert(123);
//}
}
function user(id,pwd){//创建一个user类
this.id=id;
this.pwd=pwd;
}
person.prototype.test=function () {alert("你可真棒")}//用这种方式声明方法 是创造了一片公共区域
// 实现不同对象的资源共享 减少内存
person.prototype.user=new user();
user.prototype.test2=function () {
alert("我是user");
}
//类的使用
var p1=new person("易烊千玺",21);
alert(p1.test2());//不能执行
alert(p1.user.test2());//正常执行,我是user,实现变相继承
alert(p1.address);//未报错结果undefined js会自动声明
p1.love="跳舞";//也可以直接这样声明
alert(p1.name);
var p2= new person("易",20);
alert(p1.f===p2.f);//false
alert(p1.test===p2.test);//true
</script>
类的声明
最新推荐文章于 2022-04-04 19:37:25 发布