2012-10-27 38 views
1

我從另一個JS繼承了一個類,並在Parent函數上添加了一些原型函數。當我創建一個新的兒童實例時,我想調用父類的構造函數。請建議一種方法。Node.js繼承

家長

function Parent() { .. } 
    Parent.prototype.fn1 = function(){}; 
    exports.create = function() { 
    return (new Parent()); 
}; 

兒童

var parent = require('parent'); 
Child.prototype = frisby.create(); 
function Child() { .. } 
Child.prototype.fn2 = function(){}; 
exports.create = function() { 
    return (new Child()); 
}; 

回答

0

首先,不出口創造方法,出口構造(子女,父母)。然後你就可以在孩子的父母的構造函數上調用:

var c = new Child; 
Parent.apply(c); 

關於繼承。在節點中,您可以使用util.inherits方法,該方法將設置繼承並設置超類的鏈接。如果你不需要鏈接到超類,或者只是想手動繼承,使用

Child.prototype.__proto__ = Parent.prototype; 
+0

問題是,父類是從框架。我不想更改框架的源代碼。有沒有其他方法? – user1748253

+0

當然沒有。有辦法:創建父實例,創建子實例,然後:'child.constructor.prototype .__ proto__ = parent.constructor.prototype' – Anatoliy

+0

但這是糟糕的設計。 – Anatoliy

0

父(parent.js)

function Parent() { 
} 

Parent.prototype.fn1 = function() {} 
exports.Parent = Parent; 

兒童

var Parent = require('parent').Parent, 
    util = require('util'); 

function Child() { 
    Parent.constructor.apply(this); 
} 
util.inherits(Child, Parent); 

Child.prototype.fn2 = function() {} 
+0

問題是,父類來自框架。我不想更改框架的源代碼。有沒有其他方法? – user1748253

1

你可以使用模塊util。看起來很簡單的例子:

var util = require('util'); 

function Parent(foo) { 
    console.log('Constructor: -> foo: ' + foo); 
} 

Parent.prototype.init = function (bar) { 
    console.log('Init: Parent -> bar: ' + bar); 
}; 

function Child(foo) { 
    Child.super_.apply(this, arguments); 
    console.log('Constructor: Child'); 
} 


util.inherits(Child, Parent); 

Child.prototype.init = function() { 
    Child.super_.prototype.init.apply(this, arguments); 
    console.log('Init: Child'); 
}; 

var ch = new Child('it`s foo!'); 

ch.init('it`s init!');