【问题标题】:jS OOP nested functionsjS OOP 嵌套函数
【发布时间】:2011-12-17 00:55:41
【问题描述】:

好吧,这对于 OOP 的新手来说可能是一个无厘头的问题。

我正在尝试构建一个 JS 对象库,想知道是否可以使用嵌套函数来实现它??

var object = new function() {

    this.action1 = function () {
        this.dostuff1 = function () {
             return "dostuff1";
        };

     this.dostuff2 = function () {
          return "dostuff2";
     };                   
};

我无法访问第三级功能。我可以这样嵌套吗?

this.action2 = function () {
    return "action2";
}; 

alert(object.action1.dostuff2());

【问题讨论】:

  • 您绝对可以创建嵌套函数,但您遇到的问题可能与使用 this 关键字有关。你读过how this works in JavaScript吗?这与 Java 等基于类的 OO 语言中发生的情况有点不同。
  • 缺少}; 关闭this.action1

标签: javascript oop function nested


【解决方案1】:

虽然 Eberlin 的回答完全正确,但我建议您创建一个嵌套对象,该对象又再次公开函数而不是嵌套函数本身。否则,这可能会成为可维护性的噩梦。

基本上你可以创建

var Child = function(){
   //constructor
};

Child.prototype.doStuff2 = function(){
  return "dostuff2";
};

var Root = function(obj){
   //constructor
   this.child = obj;
};

Root.prototype.action1 = function(){
   return "doStuff1";
};

//usage
var myRoot = new Root(new Child());
myRoot.action1();
myRoot.child.action2();

这是一个活生生的例子:http://jsbin.com/ijotup/edit#javascript,live

【讨论】:

    【解决方案2】:

    请参阅下面的代码清理:

    var o = (new function () {          // changed 'object' to 'o'
      this.action1 = (function () {     // added parentheses, not required.
        this.dostuff1 = (function () {  // does not return anything.
          return "dostuff1";            // and is also not the proper way to organize
        });                             // ** look at the javascript prototype
        return this;                    // now it does
      });                               // missing closing bracket
    
      this.dostuff2 = (function () {
        return "dostuff2";
      });                   
    });
    
    alert(o.action1().dostuff2());      // action1 is a function, not a variable.
    

    希望这会有所帮助。另外,这是brief tutorial on the javascript prototype

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多