2017-06-28 8 views
1

のは、私はこのコードを持っているとしましょう:モジュールのエクスポートインスタンスにアクセスできますか?

module.exports = { 
    head: { 
    title: "Some title" 
    } 
} 

は、私は助けるためにmodule.exportすなわち

module.exports = { 
    head: { 
    title: "Some title" 
    }, 
    test: function() { 
    return this.head.title 
    } 
} 

Thxを内側に、このヘッドオブジェクトへのアクセスを得ることができます。

+0

あなたができることを確認。しかし、 'test'は常にモジュール – Bergi

+0

の方法として呼ばれることを保証することはhttps://stackoverflow.com/questions/10711064/javascript-object-literal-reference-in-own-keys-function-instead-ofを見てください-theis – Bergi

+0

@Lukas私の答えはあなたの問題を解決するのに役立ちますか? – Rick

答えて

1

あなたは、参照を維持するために、関数の外にバインドを使用することができます。

var module = {}; 
 
module.exports = { 
 
    head: { 
 
    title: "Some title" 
 
    }, 
 
    test: function() { 
 
    return this.head.title 
 
    } 
 
} 
 

 
var title = module.exports.test.bind(module.exports); 
 
console.log(title());

か、参照を維持するために、関数内で適用することができます。

var module = {}; 
 
module.exports = { 
 
    head: { 
 
    title: "Some title" 
 
    }, 
 
    test: function() { 
 
    return hit.apply(module.exports.head) 
 

 
    function hit() { 
 
     return this.title; 
 
    } 
 
    } 
 
} 
 

 
console.log(module.exports.test());
そして、あなたはチャンにタイトルをしたい場合は、クラスを使用することができます。

var module = {}; 
 
class Update { 
 
    constructor(a, b) { 
 
    this.module = a; 
 
    this.string = b; 
 
    } 
 
    get titles() { 
 
    return this.module.exports = { 
 
     head: { 
 
     title: this.string || "I'm sooo defualt" 
 
     }, 
 
     test: function() { 
 
     return hit.apply(module.exports.head) 
 

 
     function hit() { 
 
      return this.title; 
 
     } 
 
     } 
 
    } 
 
    } 
 
} 
 

 

 
const newString = new Update(module, 'no way brah'); 
 
const allTheWay = new Update(module, 'all the way brah'); 
 
console.log(newString.titles.test()); 
 
console.log(allTheWay.titles.test()); 
 
const defaults = new Update(module); 
 
console.log(defaults.titles.test()); 
 
console.log('I am with the last guy,', module.exports.test());

そして、あなたは何のクラスを持っていませんでしたか。

var module = {}; 
 
module.exports = { 
 
    head: { 
 
    title: "Some title" 
 
    }, 
 
    test: function() { 
 
    return hit.apply(module.exports.head) 
 

 
    function hit() { 
 
     return this.title; 
 
    } 
 
    } 
 
} 
 

 
module.exports.head.title= 'hello world'; 
 

 
console.log(module.exports.test()); 
 

+0

タイトルの新しい値を設定するにはどうしたらいいですか?私は変更 – Lukas

+1

@lukasはい、それは可能ですが、答えを更新します。 – Rick

+0

OK、待つことができないを得るとき – Lukas

関連する問題