[英]How to call a constructor method of Parent class from child prototype in javascript?
[英]Call parent prototype from child prototype
我的父班是
function Parent() {}
Parent.prototype.get = function() {}
Parent.prototype.start= function() { this._start() }
我的孩子是
function Child(){ Parent.call(this, arguments) }
Child.prototype._start = function(){ this.get() /* error here - this.get is not a function*/ }
util.inherits(Child, Parent);
當我做
new Child().start()
我得到一個錯誤this.get is not a function
。 如何調用父原型函數? 謝謝。
由於不鼓勵使用util.inherits
,你應該使用extends
for classes,但你似乎只有常規函數,這意味着你可以在開始進一步擴展它之前將子模型設置為與父模型相同
function Parent() {} Parent.prototype.get = function() { console.log('works fine'); } Parent.prototype.start = function() { this._start(); } function Child() { Parent.call(this, arguments); } Child.prototype = Parent.prototype; Child.prototype._start = function() { this.get(); } var instance = new Child(); instance.start();
請注意,Parent和Child現在具有相同的原型,因此通過更改一個原型,您也可以更改另一個原型。
如果由於某種原因你必須避免這種情況,使用Object.create
(或assign)會這樣做
Child.prototype = Object.create(Parent.prototype);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.