我正在学习javascript,我遇到了一个疑问。为什么“this”的值在第一个示例中未定义,但在第二个示例中打印正确。示例1:varmyNamespace={myObject:{sayHello:function(){console.log("nameis"+this.myName);},myName:"john"}};varhello=myNamespace.myObject.sayHello;hello();//"nameisundefined"示例2:varmyNamespace={myObject:{sayHello:function(){console.log("Hi!My
在下面的代码中,当$(this)被调用时,jQuery是否重新查询DOM,就好像选择器已传递给它一样(使用对象的某些属性作为选择器),或者jQuery是否保留先前返回的对象?$('.someButton').on('click',function(){$(this).remove();//Isthisanotherlookup,orjustawrapperforthepreviouslyreturnedobject?}); 最佳答案 它不会重新查询DOM,this已经是一个元素。jQuery只是将上下文设置为元素,调整长度,然后返回
以下代码无效:$(".countdown").circularCountdown({startDate:$(this).attr('data-start'),endDate:$(this).attr('data-end'),timeZone:$(this).attr("timezone")});下面那个工作正常,$(".countdown").circularCountdown({startDate:$(".countdown").attr('data-start'),endDate:$(".countdown").attr('data-end'),timeZone:$(".count
我很难理解下面的代码。functionfoo(){console.log(this.a);}varobj={a:2,foo:foo};vara=4;obj.foo();setTimeout(obj.foo,100);setTimeout(obj.foo.bind(obj),100);它的输出为2、4、2,我无法理解。 最佳答案 第一种情况,obj.foo();foo中的this将指向obj,因为您已将该函数分配为该特定对象的属性。第二种情况,setTimeout(obj.foo,100);在setTimeout中,传递的函数将在窗口
Thereference状态:setState()doesnotalwaysimmediatelyupdatethecomponent.Itmaybatchordefertheupdateuntillater.Thismakesreadingthis.staterightaftercallingsetState()apotentialpitfall.Instead,usecomponentDidUpdateorasetStatecallback(setState(updater,callback)),eitherofwhichareguaranteedtofireaftertheupd
我一直不得不将this保存在一个临时变量中,以便在其他函数中访问它。例如,在下面的两个方法中,我将this保存在that变量中:startTimer:function(){varthat=this;if($('#defaultCountdown:hidden'))$('#defaultCountdown').show('slow');shortly=newDate();shortly.setSeconds(shortly.getSeconds()+5);$('#defaultCountdown').countdown('change',{until:shortly,layout:'Ne
我创建了一个小的jquery脚本,但在自定义函数中使用(this)时遇到问题。这是代码:jQuery("li").click(function(){varscrollTop=jQuery(window).scrollTop();if(scrollTop>0){jQuery('html,body').animate({scrollTop:0},'slow',function(){fadeItems();});}else{fadeItems();}});functionfadeItems(){varslogan=jQuery(this).children('p').html();jQuer
我到了thisdocument这表示这里发生了关闭:functionaddHandler(){document.getElementById('el').onclick=function(){this.style.backgroundColor='red';};}虽然这段代码移除了闭包:functionaddHandler(){varclickHandler=function(){this.style.backgroundColor='red';};(function(){varel=document.getElementById('el');el.onclick=clickHandl
所以这是一个尴尬的问题,但我正在学习NodeJS,我有一个问题。在Java中,当我从对象调用方法时,this实例保持不变(如本例所示)。privateTestinst;publicTest(){inst=this;this.myFunction();}privatevoidmyFunction(){System.out.println(inst==this);}这会返回true(理论上,这是我头脑中的代码)。但是,在NodeJS中,当我尝试做类似的事情时失败了。varMyObject=function(){this.other=newOtherObject();this.other.o
varexample=function(){console.log(typeofthis);returnthis;};在严格模式下:example.call('test')#prints'string'否则,example.call('test')#prints'object'然而,console.log(example.call('test'))版画test(如你所料)为什么Function.call更改typeof'test'==='string'绑定(bind)到this里面example? 最佳答案 当使用call()并将t