Javascript 方法的覆盖(Override)

1月 3, 2018 |

由于javascript查找方法的规则是沿着prototype 链向上查找, 当在某一级查找到该名的方法是,就停止查找。所以当我们在子类中定义同名的方法时就覆盖了父类的方法,但是我们可以通过apply或者call来改变父类方法的this指针。 示例如下:
Student 类重用Person类的构造函数和方法。

function Person(name, idno, sex){
	this.name = name;
	this.idno = idno;
	this.sex = sex;
}

Person.prototype={
	constructor: Person,
	sayHello: function(){
	    console.log("name:" + this.name + ", idno:" + this.idno 
               + ", sex:" + this.sex);
	}
}

function Student(name, idno, sex, school) {
	//注意执行person方法时需要通过Person.call来改变this变量
	Person.call(this, name, idno, sex);
	this.school = school;
}

Student.prototype = new Person(undefined, undefined, undefined);
Student.prototype.sayHello=function(){
	//通过Person.prototype.sayHello.call 改变this变量
	Person.prototype.sayHello.call(this, this.name, this.idno, this.sex);
	console.log("school:" + this.school);
}

var student = new Student("javacoder.cn", "9527", "M", "cumt");
student.sayHello();

//output
name:javacoder.cn, idno:9527, sex:M
index.jsp:34 school:cumt

Posted in: WEB开发

Comments are closed.