JavaScript中的深度嵌套函数

Deep nesting functions in JavaScript

本文关键字:嵌套 函数 深度 JavaScript      更新时间:2023-09-26

我找不到一个合适的例子来告诉我一生的挚爱如何做到这一点,即使这是可能的。根据我从exmaples片段中拼凑出来的理解,我提出了以下结构

         var t = function()
         {
             this.nestedOne = function()
             {
                 this.nest = function()
                 {
                     alert("here");
                 }
             }
         } 
         t.nestedOne.nest();

然而,这显然不起作用。如果有人能为我指明正确的方向,我将不胜感激!

只需使用:

var t = {
    nestedOne: {
        nest: function() {
            alert('here');
        }
    }
};

否则你的代码就没有意义了。函数内部的this不是指函数本身,而是指函数在其中被调用的对象上下文。您甚至没有调用代码中的函数。

如果我说obj.func(),那么func内的this将是该呼叫的obj。因此,分配this.asd = true将把true分配给该对象的"asd"属性。

如果你想做一个嵌套类,它看起来非常不同:

ClassA = (function() {
   function ClassA() {
   }
   ClassA.prototype.method1 = function() {
   };
   function ClassB() {
   }
   ClassB.prototype.method1 = function() {
   };
   return ClassA;
}())

现在只有ClassA可以生成ClassB的实例。这应该实现与java中的嵌套类相同的目标。

请参阅http://jsfiddle.net/CstUH/

function t(){
     function f(){
         this.nest = function()
         {
             alert("here");
         }
     }
     this.nestedOne = new f();
 }
var myt=new t();
myt.nestedOne.nest()

编辑1:

你也可以使用

new t().nestedOne.nest()

而不是

var myt=new t();
myt.nestedOne.nest()

(http://jsfiddle.net/CstUH/1/)

编辑2:

甚至更浓缩:

function t(){
    this.nestedOne = new function(){
        this.nest = function(){
            alert("here");
        }
    }
}
new t().nestedOne.nest()

http://jsfiddle.net/CstUH/2/

在JS中,函数是素数类对象,您可以在代码中直接访问它们[即不使用反射等]。

您放入t主体中的代码将在实际执行t:时执行

t();

您编写了t.nestedOne,nest(),但t没有nestedOne属性——您应该这样做:

var t = {
    nestedOne : {
        nest : function()
        {
            alert("here");
        }        
    }
};
t.nestedOne.nest();                ​

我建议你去参观一下John Resig的学习高级JavaScript教程,这对我来说非常有启发。

我今天写了一个简单的回调处理程序,作为如何进行深度嵌套的示例。我很抱歉,如果不是蜜蜂跪在代码风格上,它让我的概念更清晰了。

    function test () {
      this.that = this;
      this.root = this;
      this.jCallback = new Array(new Array()); // 2d
      this.jCallbackCount = -1;
      this.str = "hello";

      // Callback handler... 
      this.command = {
        that : this, // let's keep a reference to who's above us on the food chain
        root : this.root, // takes us back to the main object
        // add : function() { var that = this; console.log(that.that.str); },
        add : function(targetFnc, newFunc) { 
            var that = this; 
            var home = that.that; // pretty much root but left in as an example of chain traversal.
            var root = this.root; // useful for climbing back up the function chain
            // console.log(that.that.str); 
            home.jCallbackCount++;
            // target, addon, active
            home.jCallback[home.jCallback.length] =  { 'targetFunc' : targetFnc,  'newFunc' : newFunc,  'active' : true, 'id': home.jCallbackCount};
            console.log('cbacklength: ' + home.jCallback.length);
            console.log('added callback targetFunction:[' + targetFnc + ']');
            return home.jCallbackCount; // if we want to delete this later...      
        },
        run : function(targetFnc) {
            var that = this; 
            var home = that.that;
            console.log('running callback check for: ' + targetFnc + '  There is : ' + (home.jCallbackCount + 1) + 'in queue.');
            console.log('length of callbacks is ' + home.jCallback.length);
            for(i=0;i < home.jCallback.length - 1;i++)
            {
              console.log('checking array for a matching callback [' + targetFnc + ']...');
              console.log('current item: ' + home.jCallback[i]['targetFunc'] );
              if( home.jCallback[i]['targetFunc'] == targetFnc )
              {
                 // matched! 
                home.jCallback[i]['newFunc']();
              }
                // console.log(that.that.jCallback[i].targetFunction);
            }
        }
      };
    }
    test.prototype = {
      say : function () {
        var that = this;
        console.log('inside');
        // that.command('doSay');
        that.command.run('doSay');
        console.log(that.str);
      }

    } // end proto

    // BEGIN TESTING **************************************************************************
    // BEGIN TESTING **************************************************************************
    // BEGIN TESTING **************************************************************************
    var testing = new test();

    testing.command.add('doSay', function () { console.log('213123123'); } );
    testing.command.add('doSay', function () { console.log('12sad31'); } );
    testing.command.add('doSay', function () { console.log('asdascccc'); } );

    testing.say();

现场:http://jsfiddle.net/Ps5Uf/

  • 注意:要查看控制台输出,只需在chrome中打开检查器,然后单击"控制台"选项卡