如何调用返回的工厂函数方法?

时间:2016-12-27 13:57:37

标签: javascript

function shared() {
  return {
    lot: function() {
      console.log('crawling');
    },
    pot: function() {
      lot();
      console.log("crawled");
    }
  }
}
var share = new shared();
share.pot();

投掷

  

错误批次不是函数

如何调用lot方法

我有这样的现有功能结构,如何在不改变结构的情况下调用lot方法

1 个答案:

答案 0 :(得分:1)

this.lot();

你在一个对象(!=范围)内。您试图在Scope中获取该函数,但它不在范围内。它是同一个Object的一部分,所以使用它......

Scope:
window -> lot 
window -> pot //lot isnt in the scope, just window is

this:
 pot -> (this = Object ) this.lot = Object.lot

正如工程师指出的那样,你不需要 new ,因为它不是一个构造函数:

 share=shared();
 share.pot();