问候,
读完以下文章后,我有一个问题: https://developer.mozilla.org/en/Introduction_to_Object-Oriented_JavaScript
在继承示例中,Person 构造函数不带任何参数。如果我添加一个示例并从 Student 构造函数中调用它,那么这个示例会是什么样子?
谢谢!
最佳答案
嗯,您可以重用 Person
构造函数的逻辑的一种方法是使用 call
调用它。或apply
,例如:
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
如果您想在不带参数调用时阻止执行 Person
构造函数(如以下行:Student.prototype = new Person();
),您可以检测到它,例如:
function Person(gender) {
if (arguments.length == 0) return; // don't do anything
this.gender = gender;
}
关于javascript - 如何使用参数调用继承的 JavaScript 构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3601932/