簡體   English   中英

父訪問子原型功能

[英]Parent access child prototype function

我從以下示例中學習OOP Js。 一切都很好,很酷,我只是想知道是否可以訪問Student的原型方法sayGoodBye ,我知道可以在PHP中使用抽象方法來實現,但是想知道在JS OOP中是否可以做到這一點。 謝謝

我可能不太清楚,代碼示例很完美,只是想知道,是否可以做

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

工作代碼。

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

與PHP不同,JavaScript語言本身沒有抽象方法。 如果要在擴展原型的對象中強制實施,則可以編寫如下內容:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM