如何调用带参数的继承JavaScript构造函数? [英] How Do I Call An Inherited JavaScript Constructor With Parameters?
问题描述
问候,
阅读下面的文章后,我有一个问题:
https://developer.mozilla.org/en/Introduction_to_Object-Oriented_JavaScript
在继承示例中,Person构造函数不接受任何参数。
谢谢!
call
或 apply
,例如: function Person(gender){
this.gender = gender;
}
function Student(gender){
Person.apply(this,arguments);
}
Student.prototype = new Person(); // make Student继承自Person对象
Student.prototype.constructor = Student; // fix constructor property
var foo = new Student('male');
foo.gender; //male
foo instanceof Student; // true
foo instanceof Person; // true
如果你想阻止执行 Person
构造函数当没有参数调用时(如下面的行:
Student.prototype = new Person();
),你可以检测它, p>
function Person(gender){
if(arguments.length == 0)return; //不做任何事
this.gender = gender;
}
Greetings,
After reading the following article I have a question: https://developer.mozilla.org/en/Introduction_to_Object-Oriented_JavaScript
In the inheritance example, the Person constructor doesn't take any parameters. How would this same example look if I were to add one and call it from the Student constructor?
Thanks!
Well, a way that you can re-use the logic of the Person
constructor is invoking it with call
or apply
, for example:
function Person(gender) {
this.gender = gender;
}
function Student(gender) {
Person.apply(this, arguments);
}
Student.prototype = new Person(); // make Student inherit from a Person object
Student.prototype.constructor = Student; // fix constructor property
var foo = new Student('male');
foo.gender; // "male"
foo instanceof Student; // true
foo instanceof Person; // true
If you want to prevent the execution of the Person
constructor when is called without arguments (like in the line: Student.prototype = new Person();
), you can detect it, e.g.:
function Person(gender) {
if (arguments.length == 0) return; // don't do anything
this.gender = gender;
}
这篇关于如何调用带参数的继承JavaScript构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!