简体   繁体   English

无法通过原型函数传递

[英]Can't pass this through prototyped function

I have the following module and submodule: 我有以下模块和子模块:

// 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();

I would expect to be able to pass the api object into the City object by passing this when instantiating it. 我希望能够通过该api对象到City通过传递对象this实例化时。 But it just passes an empty object. 但是它只是传递一个空对象。

Final output: 最终输出:

loading API
{ config: 12345 }
loading City
{}

Is it not possible to pass the parent module into a submodule when instantiating it? 实例化时是否无法将父模块传递给子模块?

I think you want 我想你要

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

and

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM