2017-01-04 114 views
1

child.js父/子類層次結構中的NodeJS

class Child { 
    constructor(){ 
    this.helloWorld = "Hello World"; 
    } 
    run() { 
    } 
} 

export default new Child(); 

parent.js

import child from './child.js'; 
class Parent { 
    constructor() { 
    this.child = child; 
    } 
} 

export default new Parent(); 

index.js

import parent from './parent.js' 

console.log(parent.child.helloWorld); <-- does not throws an error, displays "Hello World" 
console.log(parent.child.run); <-- throws an error (Cannot read property run from undefined) 
console.log(parent.child.run()); <-- throws an error (Cannot read property run from undefined) 

如果我做index.js的console.log(parent.child),跑不出來,但是helloWorld屬性呢..

我怎樣才能具備的功能暴露呢?我希望能夠做到這一點,以幫助保持我的代碼更加有組織,所以將它分成單獨的類,以幫助最大限度地減少每個文件中的代碼量。

+0

要清楚:你似乎得到的錯誤與沒有出現在'console.log'輸出中的'run'無關。 –

+0

讓我重新說明它..孩子存在,我可以看到屬性「helloWorld」,但不是功能「運行」,即使他們都存在於課堂上,但「跑」似乎隱藏了,所以如果我做了控制檯。日誌(parent.child.helloWorld),它不會引發錯誤 – jaekie

+0

您有拼寫錯誤。你有父類的構造函數拼寫爲'constuctor'。如果你解決這個問題,它應該工作得很好 – ccnixon

回答

1

從一開始就明確一件事:您似乎得到的錯誤與run沒有關係,並且沒有出現在console.log輸出中。

如果您的代碼確實會拋出該錯誤,那麼這意味着parent.child的值是undefined。因此,當您撥打console.log(parent.child)時,您應該看到undefined,而不是一個對象。但是,我不明白爲什麼你會得到這個錯誤。


反正,run是在原型parent.child定義,而不是本身。 console.log最有可能顯示對象的自己的屬性(控制檯API未標準化,因此結果可能因環境而異)。 這很正常

簡單的例子來重現:

var foo = { 
 
    x: 42 
 
}; 
 
var bar = Object.create(foo); 
 
bar.y = 21; 
 
console.log(bar, bar.x, bar.y); 
 

 
// Open the browser console to see output

bar.x是可訪問的,即使console.log不顯示它(在Chrome中至少)。

0

嗯,我不知道,如果可以幫助你解決問題,但每當我想補充的產業,我用extendssuper這裏有一個例子:

基類:

class BaseDataModel { 
    constructor() { 

    } 

    getModel() { 
    return 'model'; 
    } 

module.exports.BaseDataModel = BaseDataModel; 

類擴展的基類:

"use strict" 
// Imports 
const BaseDataModel = require('../baseDataModel').BaseDataModel; // use the proper location 
class UserMembershipModel extends BaseDataModel { 
    constructor() { 
    super(); // this is optional, I use this to inherit the constructors 
    } 

    getChildModel() { 
    return super.getModel(); // This is how you access the function from your extended class 
    } 
module.exports.UserMembershipModel = UserMembershipModel; 

再次,如果它解決您的問題,因爲你的實際添加的屬性與子類不能確定。我的例子實際上是擴展(或UserMembershipModel從BaseDataModel繼承)。

希望這可以幫助你一點。