Как вызвать унаследованный конструктор JavaScript с параметрами?

Привет,

После прочтения следующей статьи у меня возник вопрос: https://developer.mozilla.org/en/Introduction_to_Object-Oriented_JavaScript

В примере наследования конструктор Person не принимает никаких параметров. Как бы выглядел этот же пример, если бы я добавил его и вызвал из конструктора Student?

Спасибо!

20
задан kgarske 30 August 2010 в 15:42
поделиться

2 ответа

Что ж, один из способов повторного использования логики конструктора 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;
}
38
ответ дан 29 November 2019 в 23:27
поделиться
// define the Person Class
function Person(name) {
    this.personname = name;
}

Person.prototype.walk = function(){};
Person.prototype.sayHello = function(){
  alert (this.personname );
};

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/constructor


Полный код:

<script>
// define the Person Class
function Person(name) {
    this.personname = name;
}

Person.prototype.walk = function(){};
Person.prototype.sayHello = function(){
  alert (this.personname );
};

// define the Student class
function Student() {}

// inherit Person
Student.prototype = new Person("test");

// correct the constructor pointer because it points to Person
Student.prototype.constructor = Student;

// replace the sayHello method
Student.prototype.sayHello = function(){
  alert('hi, I am a student and my name is \'' + this.personname + '\'' );
}

// add sayGoodBye method
Student.prototype.sayGoodBye = function(){
  alert('goodBye');
}

var student1 = new Student();
student1.sayHello();
student1.sayGoodBye();
</script>
0
ответ дан 29 November 2019 в 23:27
поделиться
Другие вопросы по тегам:

Похожие вопросы: