Javascript - 使用本地变量还是这个?
我正在使用原型方法,这是场景
function Foo () {
this.x = 5;
this.y = 2;
this.z = this.addValues();
}
Foo.prototype = {
addValues: function (){
return this.x + this.y;
}
}
显然这只是一个简单的例子;在实际项目中,“addValue”函数中会有很多活动。是否可以使用“this”关键字 100 次,或者将其缓存到本地变量有助于提高性能。例如,下面的内容会有什么不同吗?
Foo.prototype = {
addValues: function (){
var self = this;
return self.x + self.y;
}
}
I am working with prototype methods and here is the scenerio
function Foo () {
this.x = 5;
this.y = 2;
this.z = this.addValues();
}
Foo.prototype = {
addValues: function (){
return this.x + this.y;
}
}
Obviously this is just a simple example; in real project, there will be lot of activities in the 'addValue' function. Is it fine to use 'this' keyword 100s of times or caching this to local variable helps any performance improvements. For example, the below will make any difference?
Foo.prototype = {
addValues: function (){
var self = this;
return self.x + self.y;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
self.x
和this.x
之间可能没有任何有意义的区别。 可能会有所不同的是,除非您真正参与了一些尖端游戏开发或其他工作,否则这种微观优化可能不值得。首先让你的算法和数据结构达到标准,然后再担心像这样的事情。你永远不知道 JavaScript 运行时系统的开发人员何时会引入新的优化。它们无法修复错误的算法,但可以极大地影响微观优化。
There's probably no meaningful difference between
self.x
andthis.x
. What might make a difference isSuch micro-optimizations are probably not worth it unless you're really involved in some cutting-edge game development or something. Get your algorithms and data structures up to snuff first, and then worry about stuff like this last. You never know when the developers of the JavaScript runtime systems will introduce new optimizations. They can't fix your bad algorithms, but they can dramatically affect micro-optimizations.
this
是访问x
和y
的标准方法。将this
缓存到本地变量不会带来任何改进——如果有的话,首先声明self
是在浪费空间。您会看到的唯一可能风险是这样的:
话虽如此,我认为您不对人们滥用您的功能负责,而且我不会担心这一点。
另外,按照惯例,用作构造函数的函数应以大写字母开头。考虑将
foo
重命名为Foo
this
is the standard way to accessx
andy
. You'll get no improvements from cachingthis
to a local var—if anything, you're wasting space by declaringself
in the first place.The only possible risk you'd see is with something like this:
Having said that, I don't think you're responsible for people misusing your function, and I wouldn't worry about it.
Also, by convention, functions meant to be used as constructors should start with a capital letter. Consider renaming
foo
toFoo
在此示例中,将
this
分配给self
应该不会产生任何影响。 JavaScript 不会按值分配对象,而是按引用分配对象,这意味着 self 和 this 都指向同一个对象。这样做你什么也得不到。In this example, assigning
this
toself
should not make any difference. JavaScript does not assign objects by value, but rather by reference, meaning thatself
andthis
both then point to the same object. You gain nothing by doing so.