从子级调用父级的JavaScript函数原型

JavaScript function prototype calling parent from child

本文关键字:JavaScript 函数 原型 调用      更新时间:2023-09-26

我有一个愚蠢的参考问题

我声明了一个名为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

去掉这个主页上的东西。你为什么这么做?

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

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;

这很难——它应该为你指明正确的方向。

如果有多个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();

如果你只有一个应用程序,而该应用程序只有一个主页对象,你也可以通过以下方式进行:

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

这里有更多关于构造函数、原型和它的价值的信息。