如何调用带参数的继承JavaScript构造函数? [英] How Do I Call An Inherited JavaScript Constructor With Parameters?

查看:274
本文介绍了如何调用带参数的继承JavaScript构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问候,



阅读下面的文章后,我有一个问题:
https://developer.mozilla.org/en/Introduction_to_Object-Oriented_JavaScript



在继承示例中,Person构造函数不接受任何参数。



谢谢!

Person 构造函数的逻辑的方法是使用 https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/callrel =nofollow noreferrer> 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆