Bill
Bill

Reputation: 19338

Parent access child prototype function

I was learning OOP Js from the following example. It's all good and cool, i was just wondering if it's possible to access Student's prototype method sayGoodBye, i understand this can be achieve use abstract method in PHP, but just wondering is there a way to do this in JS OOP. Thanks

I may not been very clear, the code example is perfect just wondering, if can do

Person.prototype.walk = function(){
      //Goog bye is the method in Student.
      this.sayGoodBye();
};

The working code.

function Person(firstName) {
  this.firstName = firstName;
}

Person.prototype.walk = function(){
  alert("I am walking!");
};
Person.prototype.sayHello = function(){
  alert("Hello, I'm " + this.firstName);
};

function Student(firstName, subject) {
  Person.call(this, firstName);

  this.subject = subject;
};

Student.prototype = Object.create(Person.prototype); // See note below

Student.prototype.constructor = Student;

Student.prototype.sayHello = function(){
  alert("Hello, I'm " + this.firstName + ". I'm studying " + this.subject + ".");
};

Student.prototype.sayGoodBye = function(){
  alert("Goodbye!");
};

var student1 = new Student("Janet", "Applied Physics");
student1.sayHello();   // "Hello, I'm Janet. I'm studying Applied Physics."
student1.walk();       // "I am walking!"
student1.sayGoodBye(); // "Goodbye!"

alert(student1 instanceof Person);  // true 
alert(student1 instanceof Student); // true

Upvotes: 0

Views: 444

Answers (1)

Ja͢ck
Ja͢ck

Reputation: 173662

Unlike PHP, JavaScript doesn't have something like abstract methods in the language itself; if you want to force an implementation in objects that extend the prototype, you could write something like:

Person.prototype.sayGoodbye = function() {
    throw "You must implement me!";
};

Upvotes: 1

Related Questions