所以我试图以某种方式“继承”参数,我遇到了
function.apply(this, 参数)
而且它完成了这项工作......在大多数情况下都很好。我得到的是,当我从父对象调用函数时,父函数的参数位于其他函数的前面,而当我从继承者调用函数时,它们则不会。
这是我的代码:
function Human(name, gender, tel, address){
this.name = name;
this.gender = gender;
this.address = address;
this.tel = tel;
}
Human.prototype.introduce = function(){
console.log("Hi I'm " + this.name + " a " + this.gender + " from " + this.address +
". My number is " + this.tel);
}
Student.prototype = new Human;
Student.prototype.constructor = Student;
function Student(school,marks){
Human.apply(this, arguments);
this.school = school;
this.marks = marks;
}
Student.prototype.average = function(){
this.total = 0;
this.average = 0;
this.markslength = this.marks.length;
for(var i = 0; i<this.markslength; i++){
this.total = this.total + this.marks[i]
}
this.average = (this.total)/(this.markslength);
var marks3 = [6,6,2]
var Nasko = new Student('Nasko', 'Male', 14421687, 'Sofia', 'FELS', marks3);
当我这样做时: console.log(Nasko.name);
没问题。
但是当我执行 console.log(Nasko.average());
时,它给了我 NaN 。
所以我的问题是 - 如何真正“修复”它
抱歉,如果我问了一个已经问过的问题,但我真的想不出如何简单地提出这个问题,欢迎重定向到另一个类似的帖子。提前致谢。
最佳答案
您使用的前两个参数是学校和标记,它们实际上是姓名和性别。
您可以使用参数来读取最后的值
function Student(){
Human.apply(this, arguments);
var len = arguments.length;
this.school = arguments[arguments.length-2]; // second last argument is school
this.marks = arguments[arguments.length-1]; // last argument is mark.
}
关于javascript - 当使用 function.apply(this,arguments) 时,参数的顺序会混合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13316587/