我有一个独立函数,旨在使用Function.prototype.call提供的上下文。例如:functionfoo(){returnthis.bar;}>foo.call({bar:"baz"})baz有没有办法在这种情况下为this关键字提供Typescript类型注释? 最佳答案 首先,你可以使用特殊的thisparameter用于识别您期望的对象类型的语法this成为:functionfoo(this:{bar:string}){returnthis.bar;//nomoreerror}如果你直接调用它会有帮助:foo();/
我已经尝试在ie、firefox和node.js中使用以下代码varx=10;varo={x:15};functionf(){console.log(this.x);}f();f.call(o);在浏览器中的结果是10、15,但是在node.js中的结果是undefined,15。请向我解释一下“this”关键字在浏览器和node.js中的不同行为是什么?我已经阅读了很多页面,但没有任何明显的答案。提前致谢。 最佳答案 在Nodejs中加载的Javascript文件会自动包装在匿名函数中。所以在Node中你真正运行的是:(funct
我定义了一个RequireJS模块(见下文)。它是网站上每个页面都需要的功能的集合。返回对象中的一个函数initTwitter()需要调用同一对象中的另一个函数shortenURL()。我收到一个控制台错误,内容为“TypeError:this.shortenURLisnotafunction.”所有这些函数最初都在一个常规的Javascript单例对象中,代码运行良好。我是RequireJS的新手,所以我不确定this关键字在RequireJS中的工作方式是否不同,或者我只是做错了什么。编辑:我也尝试删除“this”,但我收到“ReferenceError:shortenURLisn
如果您查看Backbone.js的源代码,您会看到此模式的多种用途:this.initialize.apply(this,arguments);例如,这里:varRouter=Backbone.Router=function(options){options||(options={});if(options.routes)this.routes=options.routes;this._bindRoutes();this.initialize.apply(this,arguments);};为什么不直接写this.initialize(arguments)呢?
我知道路由用于将URL映射到模板,但显然您可以使用this.route或this.resource定义路由App.Router.map(function(){this.route("about",{path:"/about"});this.route("favorites",{path:"/favs"});});App.Router.map(function(){this.resource('posts',{path:'/posts'},function(){this.route('new');});});如果您想为路线定义子路线,您是否只使用this.resource还是有其他我没有
我找到了这个示例代码:functionpersonFullName(){returnthis.first+''+this.last;}functionPerson(first,last){this.first=first;this.last=last;this.fullName=personFullName;}vardude=newPerson("Michael","Jackson");alert(dude.fullName());这会提醒“MichaelJackson”。我将其更改为从构造函数调用personFullName而不是分配函数对象:functionpersonFullNa
问题:我怎样才能使用Triangle类扩展Point(supers(?))并组成一个如下所示的对象://"name":"ThomasTheTriangle",//"points":[//{age:"2015-05-28T06:23:26.160Z",x:1,y:1},//{age:"2015-05-28T06:23:26.161Z",x:0,y:3},//{age:"2015-05-28T06:23:26.164Z",x:2,y:3}//]JS:classPoint{constructor(x,y){this.name="Point"this.age=newDate();this.x=
在我的Reactnative代码中,我在多个模块的多个位置同时使用了bind(this)和varself=this;。两者都解决了在正确位置解析this关键字的问题。这是我的代码(执行相同功能的2个代码)-使用bind(this)retval.then(function(argument){console.log("argument"+JSON.stringify(argument));this.stateSetting(argument);}.bind(this));使用varself=thisvarself=this;retval.then(function(argument){c
我有一个svg组,我在其上调用拖动函数。varcontainer=d3.select("#id");container.call(dragcontainer);vardragcontainer=d3.drag().on("start",function(){}).on("drag",function(d,i){//(d3.select(this)).select("rect");}).on("end",function(){});显然,d3.select(this)不返回容器,但是它们相似(通过属性检查),但不完全相同。为什么会这样?如何在被调用函数中访问container?
我使用react来构建我的组件库。我需要一个index.js来将所有组件导入一个地方。像这样:MyComponents/Button.jsLabel.jsindex.js在index.js中,我接下来尝试做的是://thisexportnothingexport{default}from'./Button';//thistellsmeaboutsyntaxerrorexportdefaultfrom'./Button';我发现只有这个解决方案有效importButtonfrom'./Button';exportdefaultButton;但我发现一些React组件库使用我上面提到的语法