有一个情景,求解
student.prototype.hi覆盖了继承的person.prototype.hi,若我想通过student调用person.protype.hi时,应该怎么做。
相当于学生在学校自我介绍需要用student.prototype.hi,出来社会后需要person.prototype.hi,但不可以删除任意一个。我想知道可以通过什么参数来获得
student.prototype.hi覆盖了继承的person.prototype.hi,若我想通过student调用person.protype.hi时,应该怎么做。
相当于学生在学校自我介绍需要用student.prototype.hi,出来社会后需要person.prototype.hi,但不可以删除任意一个。我想知道可以通过什么参数来获得
2015-05-13
我好像不太理解。不过抛砖引玉,如果有哪里不对,请@ 我一声,感谢!!
首先,逻辑上,如果你需要覆盖一个方法,为什么还要调用它?
对于「学生在学校自我介绍需要用student.prototype.hi,出来社会后需要person.prototype.hi」,这应该是【学生在不同的场合说不同的话】,也就是说这个场景的都是在谈论【学生】的,跟【人】这个类没有关系。也许学生默认情况下说的 hi 就是人说的 hi,但那也是学生这个类说的。
demo1:直接写出默认值
function Person(name,age){
this.name = name;
this.age = age;
}
Person.prototype.hi = function(){
console.log("Hi,my name is "+this.name+", I'm "+this.age+" years old now.");
}
function Student(name,age,className){
Person.call(this,name,age);
this.className = className;
}
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;
Student.prototype.hi = function(where){
if(where === "school"){
console.log("Hi,my name is "+this.name+", I'm "+this.age+" years old now, and I'm from "+this.className+".");
}else{
console.log("Hi,my name is "+this.name+", I'm "+this.age+" years old now.");
}
}
var bson = new Student("Bson",27,"Class 3,Grade 2");
bson.hi();
bson.hi("school");demo2:使用Person 类的 .hi() 作为默认值
function Person(name,age){
this.name = name;
this.age = age;
}
Person.prototype.hi = function(){
console.log("Hi,my name is "+this.name+", I'm "+this.age+" years old now.");
}
function Student(name,age,className){
Person.call(this,name,age);
this.className = className;
}
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;
Student.prototype.super = Person.prototype;
Student.prototype.hi = function(where){
if(where === "school"){
this.super.hi.call(this);
console.log("I'm from "+this.className+".");
}else{
this.super.hi.call(this);
}
}
var bson = new Student("Bson",27,"Class 3,Grade 2");
bson.hi();
bson.hi("school");而对于 【被子类覆盖的 .hi() 方法】,能否通过什么参数获得?
就我认知是不可以的。
当对象调用函数时,JS 会在该对象的原型链上去寻找,找到 即 返回,而 不会 再向原型链的 上一级 去寻找。
举报