JavaScript函数原型从子进程调用父进程

时间:2014-08-29 21:17:24

标签: javascript function inheritance namespaces prototype

我有一个愚蠢的参考问题

我声明了名为MYAPP的命名空间变量

var MYAPP = MYAPP || function() {

     this.name = 'My Application';
     this.someImportantID = 123;

};

然后我想在命名空间/函数中编写代码,所以我做了

MYAPP.prototype.homepage = function() {
    urls: {
        linkOne: '/link/to/some/page/',
        linkTwo: '/link/to/some/page/'
     },
   doSomething: function() {

        // ajax call 
           $getting = $.get(this.urls.linkOne) 
        // and so on .....

        // how can I acces someImportantID ??

     }
}

然后我像这样使用它

app = new MYAPP();
app.homepage.doSomething();

但如何在 doSomething()

功能中访问 someImportantID

2 个答案:

答案 0 :(得分:0)

摆脱这个.homepage的东西。你为什么要这样做?

这是一种构造函数模式。声明你的构造函数:

var MYAPP = function(URLCollection) {

     this._name = 'My Application';
     this._someImportantID = 123;
     this._URLCollection = URLCollection;

}

然后声明实例方法:

MYAPP.prototype = {

   doSomething: function() {

        // ajax call 
           $getting = $.get(this._URLCollection.linkOne);

        // and so on .....

        // how can I acces someImportantID ??

     }
}

然后声明您的实例传递您的链接集合:

var lCollection = { linkOne: 'URL', linkTwo: 'URL' };
var myHomePage = new MYAPP(lCollection);

您可以从实例访问doSomething:

myHomePage.doSomething();

您也可以从实例中获取一些重要的ID:

myHomePage._someImportantId;

或者从实例中,通过:

this._someImportantId;

这很粗糙 - 它应该指向正确的方向。

答案 1 :(得分:0)

如果有多个MyApp实例,则可以执行以下操作:

//IIFE creating it's own scope, HomePage constructor
// is no longer globally available
;(function(){
  var HomePage = function(urls,app){
    this.urls=urls;
    this.app=app;
  }
  HomePage.prototype.doSomething=function(){
    console.log('urls:',this.urls,'app:',this.app);
  }
  //assuming window is the global   
  window.MyApp = function(urls){
    this.name='app name';
    this.homePage=new HomePage(urls,this);
  }
}());
var app = new MyApp(['url one','url two']);
app.homePage.doSomething();

如果您只有一个应用程序且该应用程序只有一个homePage对象,您也可以通过以下方式执行此操作:

var app = {
  name:'app name'
  ,homePage:{
    urls:['url one','url two']
    ,doSomething:function(){
      console.log('urls:',this.urls,'app:',app);
      //or
      console.log('urls:',app.homePage.urls,'app:',app);
    }
  }
}

app.homePage.doSomething();

有关构造函数,原型和此here的值的更多信息。