**类的声明**
每new一个对象,就会开辟一个内存空间来存储属性,即new的一个类的不同对象的相同属性会多次开辟内存存储
**类中的this,指向的是类的实例化对象,不是类本身**
function 类名(形参...)
{
this.属性=值;
this.属性=函数;
...
}
类内的属性不用声明,直接this.属性名调用
类中的函数,因为不同对象会new一次,所以函数对象不相同
声明空对象
var 变量名={}
**类的使用**
var 变量名=new 类名(形参);
变量名.属性
**类的扩充**
var p=new Person("张三",18);
p.address="bj";
alert(p.address);
var p2=new Person("李四",19);
alert(p2.address);
p对象添加了address属性,但仅作用于p对象,不作用于p2对象
**类的“继承”**
prototype变相实现继承,继承使相同变量只声明一次,减小了内存
prototype可以理解为静态属性,内存中只存一次的公共区间,类名.prototype调用
Person.prototype.t2=function(){alert("hh")};
alert(p2.t2===p.t2); //返回true,因为t2函数为两个对象共有属性,不同对象声明不会new一个函数出来
"继承"
function Person(name,age){}
function User(uname,pwd)
{
this.uname=uname;
this.pwd=pwd;
this.f="唱";
}
Person.prototype.user=new User(); //将user对象放在公共域,声明的其他对象就不用为其开辟空间
User.prototype.U=function(){alert("我是user")};
p.user.U();
alert(p.user.f);
代码示例:
<html
>
<head
>
<title
>js 自定义类的学习
</title
>
<meta charset
="utf-8"/>
<script type
="text/javascript">
function Person(name
,age
){
this.name
=name
;
this.age
=age
;
this.test=function(a
){
alert(a
);
}
}
var p
=new Person("张三",18);
var p2
=new Person("李四",19);
function User(uname
,pwd
)
{
this.uname
=uname
;
this.pwd
=pwd
;
this.f
="唱";
}
Person
.prototype
.t2=function(){alert("hh")};
Person
.prototype
.user
=new User();
User
.prototype
.U=function(){alert("我是user")};
p
.user
.U();
alert(p
.user
.f
);
</script
>
</head
>
<body
>
</body
>
</html
>