2015-12-07 26 views
0

通过这个我有以下的模块和子模块:无法通过原型功能

// Parent module "API" 
var API = function(){ 
    console.log('loading API'); 
    this.param = 12345; 
} 

// A method for instantiating the City module via the API 
API.prototype.City = function(){ 
    return City(this);   // <--- Can't pass this here? 
} 

// Submodule "City" 
var City = function(api){ 
    console.log("loading City"); 
    console.log(api);   // <--- Just prints empty object {} 
} 

var api = new API(); 
console.log(api); 
var denver = new api.City(); 

我希望能够通过传递this实例化时,它给api对象传递到City对象。但它只是传递一个空的对象。

最终输出:

loading API 
{ config: 12345 } 
loading City 
{} 

是没可能实例化时,它的父模块传递到一个子模块?

+2

究竟你使用'新ap​​i.City()''的关键字new'打算怎么办?这将使用新创建的对象作为this的值来调用该函数。 – Pointy

+0

对我而言,'api'参数在控制台中显示为'API.City',这就是它应该是 – adeneo

+0

@adeneo你可以拿出一个小提琴来演示它的工作吗? –

回答

1

我想你想

API.prototype.City = function(){ 
    return new City(this); 
//   ^^^ 
} 

… 
var denver = api.City(); 
//    ^^^^^^^ standard *method* call