js中某个类的prototype原型类型的属性。
子类可以直接调用.
譬如
1. 直接用 WuYouUser.prototype.Count
2. 使用Wo.Count
备注:Wo是WuYouUser类的实例.
--------------------------------------------------------------------------------------------------------------------
1,对象创建方式
1)对象初始化器方式
格式:objectName = {property1:value1, property2:value2,…, propertyN:valueN}
property是对象的属性
value则是对象的值,值可以是字符串、数字或对象三者之一
例如: var user={name:“user1”,age:18};
var user={name:“user1”,job:{salary:3000,title:programmer}
以这种方式也可以初始化对象的方法,例如:
var user={name:“user1”,age:18,getName:function(){
return this.name;
}
}
后面将以构造函数方式为重点进行讲解,包括属性和方法的定义等等,也针对构造函数的方式进行讲解。
2)构造函数方式
编写一个构造函数,并通过new方式来创建对象,构造函数本可以带有构造参数
例如:
function User(name,age){
this.name=name;
this.age=age;
this.canFly=false;
}
var use=new User();
--------------------------------------------------------------------------------------------------------------------
3)类属性定义
语法格式:functionName.propertyName=value
例如:
function User(){ }
User.MAX_AGE=200;
User.MIN_AGE=0;
alert(User.MAX_AGE);
参考JS标准对象的类属性:
Number.MAX_VALUE //最大数值 Math.PI //圆周率
--------------------------------------------------------------------------------------------------------------------
定义实例方法,目前也可以使用两种方式:
prototype方式,在构造函数外使用,语法格式:
functionName.prototype.methodName=method;
或者
functionName.prototype.methodName=function(arg1,…,argN){};
this方式,在构造函数内部使用,语法格式:
this.methodName=method;
或者
this.methodName=function(arg1,…,argN){};
上面的语法描述中,method是外部已经存在的一个方法,methodName要定义的对象的方法,意思就是将外部的一个方法直接赋给对象的某个方法。
以function(arg1,…,argN){}的方式定义对象方法是开发人员应该掌握的。
个人总结:***methodName=method;***methodName=function(arg0,arg1...){....};
--------------------------------------------------------------------------------------------------------------------
4)定义类方法
类方法需要在构造函数外面定义,可以直接通过构造函数名对其进行引用。
语法格式:
functionName.methodName=method;
或者
functionName.methodName=function(arg1,…,argN){};
例子:
function User(name){
this.name=name;
}
User.getMaxAge=getUserMaxAge;
function getUserMaxAge(){
return 200;
}
或者
User.getMaxAge=function(){return 200;};
alert(User.getMaxAge());
--------------------------------------------------------------------------------------------------------------------
5,属性与方法的动态增加和删除
1)对于已经实例化的对象,我们可以动态增加和删除它的属性与方法,语法如下(假定对象实例为obj):
动态增加对象属性
obj.newPropertyName=value;
动态增加对象方法
obj.newMethodName=method或者=function(arg1,…,argN){}
动态删除对象属性
delete obj.propertyName
动态删除对象方法
delete obj.methodName
2)例子:
function User(name){
this.name=name;
this.age=18;
}
var user=new User(“user1”);
user.sister=“susan”;
alert(user.sister);//运行通过
delete user.sister;
alert(user.sister);//报错:对象不支持该属性
user.getMotherName=function(){return “mary”;}
alert(user.getMotherName());//运行通过
delete user.getMotherName;
alert(user.getMotherName());//报错:对象不支持该方法
个人观点:备注_上面的functionName你可以立即为类.