【问题标题】:Simplify the code by using cycle function使用循环函数简化代码
【发布时间】:2015-11-03 00:07:43
【问题描述】:

我有多个使用相同循环代码的函数,我想知道是否可以通过一个循环函数来简化代码,这样我就可以通过调用想要的函数名称来执行代码。

现在:

for(var i=0;i<all;i++){ someFunction(i) }

需要:

cycle(someFunction);
function cycle(name){
    for(var i=0;i<all;i++){
       name(i);
    }
}

我尝试通过使用“窗口”来执行此操作,但我没有收到错误,但该函数未执行。

var MyLines = new lineGroup();
MyLines.createLines(); // works
MyLines.addSpeed();    // doesn't work


var lineGroup = function(){
    this.lAmount = 5,
    this.lines = [],

    this.createLines = function (){
        for(var i=0,all=this.lAmount;i<all;i++){
            this.lines[i] = new line();
        }
    },

    this.addSpeed = function (){
        // no error, but it's not executing addSpeed function
        // if i write here a normal cycle like in createLines function
        // it's working ok
        this.linesCycle("addSpeed");
    },
    this.linesCycle = function(callFunction){
        for(var i=0,all=this.lAmount;i<all;i++){
            window['lineGroup.lines['+i+'].'+callFunction+'()'];
        }
    }
}

var line = function (){
    this.addSpeed = function (){
        console.log("works");
    }
}

【问题讨论】:

    标签: javascript cycle simplify


    【解决方案1】:
    window['lineGroup.lines['+i+'].'+callFunction+'()'];
    

    字面意思尝试访问以lineGroups.lines[0] 开头的属性。只有当您明确执行 window['lineGroups.lines[0]'] = ... 时,这样的属性才会存在,我确定您没有这样做。

    根本不需要window。只需访问对象的line 属性:

    this.lines[i][callFunction]();
    

    我没有收到错误,但函数没有执行。

    访问不存在的属性不会产生错误。示例:

    window[';dghfodstf0ap9sdufgpas9df']

    这试图访问属性;dghfodstf0ap9sdufgpas9df,但由于它不存在,这将导致undefined。由于没有对返回值做任何事情,因此无法观察到任何变化。

    【讨论】:

    • 像魅力一样工作 ;)
    【解决方案2】:

    没有名称空间使用:

    window["functionName"](arguments);
    

    所以把它包装起来并这样使用它:

    cycle(someFunction);
    function cycle(name){
        for(var i=0;i<all;i++){
           window[name](i);;
        }
    }
    

    使用命名空间,包括:

    window["Namespace"]["myfunction"](i);
    

    【讨论】:

      【解决方案3】:

      请注意,这可能有点矫枉过正,但使用一个函数来创建一个类对象(你可以用谷歌搜索 makeClass 以及它为什么/可能有用)你可以创建对象的实例。

      // makeClass - By Hubert Kauker (MIT Licensed)
      // original by John Resig (MIT Licensed).
      function makeClass() {
          var isInternal;
          return function (args) {
              if (this instanceof arguments.callee) {
                  if (typeof this.init == "function") {
                      this.init.apply(this, isInternal ? args : arguments);
                  }
              } else {
                  isInternal = true;
                  var instance = new arguments.callee(arguments);
                  isInternal = false;
                  return instance;
              }
          };
      }
      var line = function () {
          this.addSpeed = function () {
              console.log("works");
          };
      };
      var LineGroup = makeClass();
      
      LineGroup.prototype.init = function (lineNumber) {
          this.lAmount = lineNumber?lineNumber:5,
          this.lines = [],
      
          this.createLines = function (mything) {
              console.log(mything);
              var i = 0;
              for (; i < this.lAmount; i++) {
                  this.lines[i] = new line();
              }
          },
      
          this.addSpeed = function () {
              console.log("here");
              this.linesCycle("addSpeed");
          },
          this.linesCycle = function (callFunction) {
              console.log("called:" + callFunction);
              var i = 0;
              for (; i < this.lAmount; i++) {
                  this.lines[i][callFunction]();
              }
          };
      };
      var myLines = LineGroup();
      myLines.createLines("createlines"); 
      myLines.addSpeed();
      //now add a new instance with 3 "lines"
      var newLines = LineGroup(3);
      newLines.createLines("createlines2")
      console.log("addspeed is a:" + typeof newLines.addSpeed);
      console.log("line count"+newLines.lAmount );
      newLines.addSpeed();
      

      【讨论】:

        猜你喜欢
        • 2023-04-07
        • 2021-08-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多