1.实例属性
function O(x,y){
this.x = x;
this.y = y;
}
x和y为类O的实例属性,与Java的普通属性一样,实例属性只能通过类O的对象来访问,如o.x
2.实例方法
function O(x,y){
this.x = x;
this.y = y;
this.show = function() {
return "{x:" + x + ",y:" + y + "}";
}
}
show为类O的实例方法,实例方法体内可以直接访问实例属性,同样实例方法只能通过类O的对象来访问,如o.show()
3.类属性
O.z = 1;
z为类O的类属性,类属性直接通过类来访问,与Java不同的是,类属性不能通过类的对象来访问
4.类方法
O.method = function(x) {
return x * x;
}
method为类O的类方法,类方法直接通过类来访问;同样地,类方法不能通过类的对象来访问
5.类的继承
// 父类构造函数,定义父类属性
Person = function(name, age) {
this.name = name;
this.age = age;
}
// 定义父类方法
Person.prototype.talk = function() {
alert("Hello, " + this.name);
}
// 子类构造函数,定义子类属性
Teacher = function(name, age, course) {
Person.apply(this, arguments);
this.course = course;
}
// 继承Person类
Teacher.prototype = new Person('',0);
Teacher.prototype.constructor = Teacher;
// 定义子类自己的方法
Teacher.prototype.teach = function() {
alert(this.name + " teach " + course);
}