道场的要求和范围

道场的要求和范围

问题描述:

任何人都可以向我解释为什么当drawSection被称为“这个”的价值成为全球范围?道场的要求和范围

是否有反正在这里使用require而不必在另一个变量保存widget之前我失去它?

define("my/TextBox", [ 
    "dojo/_base/declare", 
    "dijit/form/ValidationTextBox" 
], function(
declare, ValidationTextBox 
) { 

    function drawSection() { 
     alert(this); 
     require(["dojo/dom-construct"], function(domConstruct) { 
     alert(this); // this = window 
     }); 
    };  

    return declare([ValidationTextBox], { 
     postCreate: function() { 
      this.inherited(arguments);    
      drawSection.call(this) 
     } 
    }); 
}); 

它退出使用简单dojo/_base/langhitch()功能来解决这个问题。

因为require(["dojo/dom-construct"], function(domConstruct) {....})内部的功能指的全球背景下,

所以用lang.hitch功能在目前情况下(通过使用this)和probleme解决

这里是一个Fiddle

和以上工作片段:

define("my/TextBox", [ 
 
\t "dojo/_base/lang", 
 
    "dojo/_base/declare", 
 
    "dijit/form/ValidationTextBox" 
 
], function(lang, 
 
    declare, ValidationTextBox 
 
) { 
 

 
    function drawSection() { 
 

 
    alert(this); 
 

 
    require(["dojo/dom-construct"], lang.hitch(this,function(domConstruct) { 
 

 
     alert(this); // this = window 
 

 
    })); 
 

 
    }; 
 
    return declare([ValidationTextBox], { 
 
    postCreate: function() { 
 
     this.inherited(arguments); 
 
     drawSection.call(this) 
 
    } 
 
    }); 
 
    
 
}); 
 

 

 
require([ 
 
    "dojo/parser", 
 
    "my/TextBox", 
 
    "dojo/domReady!" 
 
], function(
 
    parser, 
 
    TextBox 
 
) { 
 
    
 
    // important: parse document after the ValidationTextBox was extended 
 
    parser.parse(); 
 
    
 
});
<link href="https://ajax.googleapis.com/ajax/libs/dojo/1.8/dijit/themes/claro/claro.css" rel="stylesheet"/> 
 
<script src="//ajax.googleapis.com/ajax/libs/dojo/1.10.4/dojo/dojo.js"></script> 
 

 
<body class="claro"> 
 
<input type="text" data-dojo-type="my/TextBox" />, 
 
</body>

+0

感谢您的提示....为什么它恢复到全球范围虽然? – blu10

+1

它需要调用者定义的作用域('require'),它是'window'' – ben

+0

就像ben说的那样,然后'lang.hitch(this,function(){})'表示执行'this'中的函数参考当前类,如果我们声明'lang.hitch(window,function(){})',它将在'window'范围内执行而不是类。 –

您需要使用dojo/_base/langlang.hitch这样的:

require(["dojo/dom-construct"], lang.hitch(this, function(domConstruct) { 

     alert(this); // this = window 

    })); 

这是一个常见的问题关闭。
https://dojotoolkit.org/reference-guide/1.10/dojo/_base/lang.html#hitch

作为一个很好的做法,我会建议有小部件内drawSection方法和顶部所需的dom-construct(你永远需要它,你从postCreate称它为所以“按需”要求是矫枉过正)

define("my/TextBox", [ 
     "dojo/_base/declare", 
     "dijit/form/ValidationTextBox", 
     "dojo/dom-construct" 
    ], function(declare, ValidationTextBox, domConstruct) { 

    return declare([ValidationTextBox], { 
     postCreate: function() { 
       this.inherited(arguments);    
       this.drawSection() 
     }, 
     drawSection: function() { 
       alert(this); 
       //domConstruct.whaever you want 
     }; 
    }); 
    });