views:

35

answers:

2

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!

A: 
// 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


The full code:

<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>
Floyd
I think this works fine if you always want "test" as the person name, but this is not what I mean when I ask to call it from the Student constructor.
+2  A: 

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;
}
CMS
Thanks, this is exactly what I needed to know.
@kgarske: You're welcome!
CMS