[英]Javascript call method from super class
我嘗試在學生對象中的hello函數中調用方法doSomething,而沒有原型,只需將其附加在此即可。 學生擴展Person對象。
function Person(name){
this._name = name;
this.doSomething = function () {
console.log('doSomething');
}
}
function Student (name, grade) {
this._name = name;
this._grade = grade;
this.hello = function () {
//How i can call doSomething() here
}
}
你需要.call()
父在構造使Student
擁有一切Person
做,然后做this.doSomething()
function Student (name, grade) {
Person.call(this, name); // extends
this._grade = grade;
this.hello = function () {
this.doSomething();
};
}
然后您可以從學生實例調用hello()
:
var student = new Student("t","A")
student.hello(); // logs 'doSomething'
您的代碼應該是(帶有正確的JS類擴展名):
function Person(name){
this._name = name;
}
Person.prototype.doSomething = function() {
console.log('doSomething');
}
function Student (name, grade) {
this._name = name;
this._grade = grade;
}
Student.prototype = Object.create(Person.prototype); // extends
Student.prototype.hello = function () {
// Just call it like this:
this.doSomething();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.