1、类和成员的访问控制:使用this关键字或者prototype定义的属性和方法是公共成员。使用var关键字定义的成员为私有成员,不能为外部所访问。
2、创建子类方法
function Person(myName,myAge){
this.name = myName;
this.age = myAge;
this.showInfo = function(){
return"我的年龄是"+this.age;
}
}
function Child(){}
Child.prototype = new Person();
var child_1 = new Child();
child_1.name="jane";
child_1.age = 20;
console.log(child_1.showInfo());
3、使用基类的构造器方法
function Person(myName,myAge){
this.name = myName;
this.age = myAge;
this.showInfo = function(){
return"我的年龄是"+this.age;
}
}
function Child(myName,myAge){
this.$super = Person;
this.$super(myName,myAge);
}
Child.prototype = new Person();
var child_1 = new Child("jane",8);
child_1.showInfo();
使用$super访问基类的完整应用
Object.prototype.$super=function(){
var result;
try{
//首先获取基类的构造器,将它保存在变量result中
result = eval(this.constructor).prototype.constructor;
//调用基类的构造器方法
result.apply(this,arguments);
}
catch(err){
//如果不是内建类或者自定义类,或者不在构造器中调用该方法,那么抛出错误
throw new Error("only can be used in constructor!");
}
return result;
}
function Person(){
if(arguments.length>2){
throw new Error("Two arguments only can be allowed");
}
this.nickName = arguments[0];
this.age = arguments[1];
}
Person.prototype.showInfo = function(){
return ("嗨! 我的名字是"+this.nickName);
}
function Child(myName,myAge){
this.$super(myName,myAge);
}
Child.prototype = new Person();
var child_1 = new Child("jane",8);
child_1.showInfo();
4、静态成员、静态类
方法:只需将属性或者方法赋给类本身
function Person(myName,myAge){
this.name = myName;
this.age = myAge;
}
Person.showInfo = function(){
return("嗨,我的性别是"+this.sex);
}
Person.sex = "男";
静态方法中,只能访问静态属性sex
静态成员不能被继承,但是可以传播。
5、覆载
方法覆载,在子类重定义一个同名的方法,属性覆载,需要使用get和set存取器定义属性。
6、原型链本质论
每一个类都有一个prototype属性,这是一个静态属性。该属性值包含了标识该类的一个对象,这个对象成为原型对象。
在原型对象上定义了一些内部属性,用于描述该类,其中包括该类的基类的信息。通过该信息,javascript解释引擎就能知道该类的基类。该描述基类信息的内部属性成为【Prototype】,