kga*_*ske 20 javascript parameters constructor
问候,
阅读以下文章后,我有一个问题:https: //developer.mozilla.org/en/Introduction_to_Object-Oriented_JavaScript
在继承示例中,Person构造函数不接受任何参数.如果我要添加一个并从Student构造函数中调用它,那么同样的例子怎么样?
谢谢!
CMS*_*CMS 38
好吧,一种可以重用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
Run Code Online (Sandbox Code Playgroud)
如果你想在Person
没有参数的情况下调用构造函数的执行(比如在行:) Student.prototype = new Person();
,你可以检测到它,例如:
function Person(gender) {
if (arguments.length == 0) return; // don't do anything
this.gender = gender;
}
Run Code Online (Sandbox Code Playgroud)
接受的答案似乎是不正确的.根据Mozilla关于OO JavaScript的说法,正确的方法是:
var Person = function(firstName) {
this.firstName = firstName;
};
function Student(firstName, subject) {
// Call the parent constructor, making sure (using Function#call)
// that "this" is set correctly during the call
Person.call(this, firstName);
// Initialize our Student-specific properties
this.subject = subject;
};
// Create a Student.prototype object that inherits from Person.prototype.
// Note: A common error here is to use "new Person()" to create the
// Student.prototype. That's incorrect for several reasons, not least
// that we don't have anything to give Person for the "firstName"
// argument. The correct place to call Person is above, where we call
// it from Student.
Student.prototype = Object.create(Person.prototype); // See note below
// Set the "constructor" property to refer to Student
Student.prototype.constructor = Student;
// Example usage:
var student1 = new Student("Janet", "Applied Physics");
Run Code Online (Sandbox Code Playgroud)
您可以清楚地看到,Mozilla指定使用"new Person()"创建Student.prototype是一个常见错误.因此,接受的答案具有误导性.
我实际上已经在我正在进行的项目中对此进行了测试,并且Mozilla的方式是正确的,而上述答案不起作用.
归档时间: |
|
查看次数: |
7895 次 |
最近记录: |