2017-02-28 72 views
0

在原型繼承的簡單示例中,我想將Person對象設置爲Student對象的父類,但我不想在設置Student類的原型的時間,因爲這將是錯誤的。但不知何故,這段代碼不起作用。任何幫助?如何在不使用新關鍵字的情況下設置原型功能

var Person = function(name) { 
    var that = this; 
    this.name = name; 
    var _log = function() { 
    console.log("Hello", that.name) 
    }; 
    return { 
    log: _log 
    }; 
}; 

var Student = function(name) { 
    Person.call(this, name); 
    var _getCollegeName = function() { 
    console.log("MIT") 
    }; 
    return { 
    getCollegeName: _getCollegeName 
    }; 
}; 

Student.prototype = Object.create(Person); 
//Student.prototype = new Person("Soham"); want to avoid this as the value should be passed from child class 

var s = new Student("Soham"); 
s.log(); 
//s.getCollegeName(); 
+0

即使我使用'Student.prototype =新的Person的代碼不工作( 「Soham」)'而不是'Object.create' –

回答

1

您可以設置getCollegeNamePerson()呼叫的屬性,返回Person對象

var Person = function(name) { 
 
    var that = this; 
 
    this.name = name; 
 
    var _log = function() { 
 
    console.log("Hello", that.name) 
 
    }; 
 
    return { 
 
    log: _log 
 
    }; 
 
}; 
 

 
var Student = function(name) { 
 
    var p = Person.call(this, name); 
 

 
    var _getCollegeName = function() { 
 
    console.log("MIT") 
 
    }; 
 

 
    p.getCollegeName = _getCollegeName; 
 

 
    return p 
 
}; 
 

 
Student.prototype = Object.create(Person); 
 
//Student.prototype = new Person("Soham"); want to avoid this as the value should be passed from child class 
 

 
var s = Student("Soham"); 
 
s.log(); 
 
s.getCollegeName();

相關問題