日期:2014-05-16  浏览次数:20339 次

JavaScript实现类的继承
下面是常用的js类继承的方式,我们继承一下上篇文章中的Person类:
function Person(name, age, email){
	this.name = name;
	this.age = age;
	this._email = email;
}

function _Person_show_me(){
	alert('我叫' + this.name + ',我' + this.age + '岁了,我的email是' + this._email);
}

Person.prototype.show_me = _Person_show_me;

function Student(name, age, email, score){
	Person.call(this, name, age, email);
	this.score = score;
}

function _Student_show_score(){
	alert("我的分数是:" + this.score);
}

Student.prototype = new Person();
Student.prototype.show_score = _Student_show_score;

var he = new Student('小何', 28, 'baijun.he@163.com', 80);
he.show_me();
he.show_score();


  1. 使用了js的call()方法调用父类的构造函数。第一个参数是this,当实例化Student时,这个this就表示he这个对象。后面的参数就是调用的函数Person的参数。
  2. Student.prototype = new Person();通过这个语句把Person类的属性和方法传递给Student类。这里只传递了方法,属性我们通过上面的call方法定义了。
  3. 为什么在 new Person();中没有传递参数呢?这是原型链的标准做法。要确保构造函数没有任何参数。我们通过call方法实现参数的赋值。
  4. Student.prototype.show_score = _Student_show_score;必须在 Student.prototype = new Person();后面调用,因为执行 Student.prototype = new Person();时Student的prototype属性被替换成了新的对象,以前的属性和方法会被删除。