2015-05-31 57 views
0

嘗試執行如下自定義任務:入門的咕嚕任務自定義函數執行未定義

'use strict'; 
module.exports = function(grunt) { 
    grunt.initConfig({ 

     log: { 
      one: [1, 2, 3], 
      two: "Hello World", 
      three: true, 
      four: { 
       five: function() { 
        grunt.log.writeln("Hi"); 
       }, 
       six: function() { 
        grunt.log.writeln("Welcome"); 
       } 
      } 
     } 

    }); 
    grunt.registerMultiTask('log', 'Log stuff', function() { 
     grunt.log.writeln(this.target + ": " + this.data + "\n"); 

     if (this.target === 'four') { 
      console.log(this.data); 

      for(var d in this.data) { 
       console.log(this.data['five']()); 

       console.log(this.data['six']()); 
      } 
     } 
    }); 

    grunt.registerTask('default', 'log'); 
}; 

我得到以下的輸出:

Running "log:one" (log) task 
one: 1,2,3 

Running "log:two" (log) task 
two: Hello World 

Running "log:three" (log) task 
three: true 

Running "log:four" (log) task 
four: [object Object] 

{ five: [Function], six: [Function] } 
Hi 
undefined 
Welcome 
undefined 
Hi 
undefined 
Welcome 
undefined 

Done, without errors. 

我不能夠在執行功能五理解和六;它顯示正確的輸出「undefined」。從這個未定義的地方來?

回答

1

當你寫console.log(this.data['five']());它的意思是「打印出在this.data.five定義的函數的返回值,即:

function() { 
    grunt.log.writeln("Hi"); 
} 

該函數沒有明確的return,所以它的返回值是undefined,和。您的代碼打印出來 爲了避免這種情況,你的代碼更改爲:

for(var d in this.data) { 
    this.data['five'](); 
    this.data['six'](); 
} 

甚至更​​好,避免重複:

for(var d in this.data) { 
    this.data[d](); 
} 
+0

感謝幫助。我在想這是與Grunt配置不匹配或類似的問題有關,但是我也在這裏得到了我的答案:https://github.com/gruntjs/grunt/issues/1340 –