【问题标题】:Prototype into a Closure Object原型化为闭包对象
【发布时间】:2017-03-23 22:21:25
【问题描述】:

因此,作为一项工作要求,我们的代码不能超过 80 列和 250 行。这意味着我必须回去将我的代码分解成更小的文件,并且我正在探索一些选项。首先想到的是 prototyping 和 JavaScript,因为我无法安装 RequireJS。其次,我的应用程序使用了闭包。我的问题是:你能把原型做成一个闭包吗?下面的例子。

文件 #1

var app = (function () {
  var _userName = "Steve";
  function sayHello() {
    return "Hello " + _userName;
  }
  return {
    sayHello: sayHello
  }
})();

文件 #2

app.prototype.sayGoodbye = function() {
  return "Goodbye " + _userName;
};

输出

app.sayHello(); // should output "Hello Steve"
app.sayGoodbye(); // should output "Goodbye Steve"

但这似乎不起作用,因为 sayGoodbye() 函数不包含在闭包中。但是,如果告诉sayHello() 函数使用sayGoodbye(),那也不起作用。关于如何跨多个文件构造闭包对象的任何建议?谢谢!

【问题讨论】:

标签: javascript closures


【解决方案1】:

您可以像这样更改closure function,这是closure function,看起来更像class

var app = (function() {

  // This is your constructor
  function app() {
    this._userName = "Steve";
  }

  function hello() {
    return "Hello " + this._userName;
  }

  // This is made to do the above function hello() public
  app.prototype.sayHello = function() {
    return hello.call(this);
  }

  // Here we return the app object to be able to do a prototype
  return app;
})();

// Here we do our prototype
app.prototype.sayGoodbye = function() {
  return "Goodbye " + this._userName;
}

// Here we create an instance
var a = new app();

console.log(a.sayHello()); // should output "Hello Steve"
console.log(a.sayGoodbye()); // should output "Goodbye Steve"

【讨论】:

  • 太棒了,谢谢。我要试一试并报告。如果我想使用单个变量怎么办?
  • 好吧,就像我的回答所示,您可以创建一个应用实例并通过所有代码使用它
  • 哦,我明白了。呃。需要更多的睡眠!谢谢!
猜你喜欢
  • 2015-02-28
  • 2011-04-03
  • 1970-01-01
  • 2012-09-28
  • 2016-02-10
  • 1970-01-01
  • 1970-01-01
  • 2020-06-08
  • 2016-11-05
相关资源
最近更新 更多