阜宁网站建设公司,在线网页转pdf,商丘网站,个人如何做短视频网站首先#xff0c;用一句话来概括scope的作用#xff1a;scope就是用来解决 js 中 this 的指向问题。 下面进行讨论#xff1a; 1、 关于JavaScript中this的使用#xff0c;这是一个由来已久的问题了。我们这里就不介绍它的发展历史了#xff0c;只结合具体的例子#xff… 首先用一句话来概括scope的作用scope就是用来解决 js 中 this 的指向问题。 下面进行讨论 1、 关于JavaScript中this的使用这是一个由来已久的问题了。我们这里就不介绍它的发展历史了只结合具体的例子告诉大家可能会遇到什么问题在遇到这些问题时EXT是如何解决的。在使用EXT时最常碰到的就是使用Ajax回调函数时出现的问题如下面的代码所示。 input typetext nametext idtextinput typebutton namebutton idbutton valuebutton 现在的HTML 页面中有一个text输入框和一个按钮。我们希望按下这个按钮之后能用Ajax去后台读取数据然后把后台响应的数据放到text中实现过程如代码清单10-6所示。 代码清单10-6 Ajax中使用回调函数 function doSuccess(response) {text.dom.value response.responseText;} Ext.onReady(function(){Ext.get(button).on(click, function(){var text Ext.get(text);Ext.lib.Ajax.request(POST,08.txt,{success:doSuccess},param encodeURIComponent(text.dom.value));});}); 在上面的代码中Ajax已经用Ext.get(text)获得了text以为后面可以直接使用没想到回调函数success不会按照你写的顺序去执行。当然也不会像你所想的那样使用局部变量text。实际上如果什么都不做仅仅只是使用回调函数你不得不再次使用Ext.get(text)重新获得元素否则浏览器就会报text未定义的错误。 在此使用Ext.get(text)重新获取对象还比较简单在有些情况下不容易获得需要处理的对象我们要在发送Ajax请求之前获取回调函数中需要操作的对象有两种方法可供选择scope和createDelegate。 为Ajax设置scope。 function doSuccess(response) {this.dom.value response.responseText;}Ext.lib.Ajax.request(POST,08.txt,{success:doSuccess,scope:text},param encodeURIComponent(text.dom.value)); 在Ajax的callback参数部分添加一个scope:text把回调函数的scope指向text它的作用就是把doSuccess函数里的this指向text对象。然后再把doSuccess里改成this.dom. value这样就可以了。如果想再次在回调函数里用某个对象必须配上scope这样就能在回调函数中使用this对它进行操作了。 为success添加createDelegate()。 function doSuccess(response) {this.dom.value response.responseText;} Ext.lib.Ajax.request(POST,08.txt,{success:doSuccess.createDelegate(text)},param encodeURIComponent(text.dom.value)); createDelegate只能在function上调用它把函数里的this强行指向我们需要的对象然后我们就可以在回调函数doSuccess里直接通过this来引用createDelegate()中指定的这个对象了。它可以作为解决this问题的一个备选方案。 如果让我选择我会尽量选择scope因为createDelegate是要对原来的函数进行封装重新生成function对象。简单环境下scope就够用了倒是createDelegate还有其他功能比如修改调用参数等。 2、再通过几个简单的例子来解释 code is below htmlheadscriptvar p1 { name: p1, fn: function() { var scope this.scope? this.scope:this; alert(scope.name) }};var p3 { name: p3};var p2 { name: p2, //scope: p1, // assign scope fn: p1.fn // copying p1.fn loses its scope};p1.fn();p2.fn();/script/head/html Running that code will pop up two times: p1 and p2 ... even though p2s fn uses the fn from p1 but since it is run within p2 scope, itdisplays p2s name. Uncomment the scope config in p2 and refresh. Now the page will pop up p1 two times. Set the scope config option to point to p3 and refresh. Now the page will pop up p1 and p3. All the above behaviors are made possible since the p1.fn function takes the scope into consideration. Ext, on the other hand, uses a转载于:https://www.cnblogs.com/yin-jingyu/archive/2011/08/03/2126460.html