简体   繁体   English

局部变量对JavaScript中对象属性开销的引用

[英]Local variable reference to object property overhead in JavaScript

Is it a bad practice to use a local variable as reference to an object property instead of the property itself? 使用局部变量而不是属性本身来引用对象属性是一种不好的做法吗?

function Apple(){
  this.type = 'green appale';
}

Apple.prototype.slice = function(){
  //Does this create a noticeable overhead?
  var type = this.type;

  //slicing action

}

The answer is both yes and no. 答案是是和不是。 From a performance stand point don't worry about it. 从性能的角度来看,不必担心。 This is a cake walk compared to other performance issues. 与其他性能问题相比,这简直是小菜一碟。 Besides the rule of thumb is to write code for readability and only optimize when you need to through profiling after the fact. 除了经验法则之外,还要编写代码以提高可读性,并且仅在需要根据事实进行概要分析时才进行优化。 Don't pre optimize. 不要预先优化。

As for the caveats… If the value you are saving as an immutable value (string, int, boolean) then your are 100% safe do do this. 注意事项...如果您将值保存为不可变值(字符串,整数,布尔值),那么您100%安全就可以这样做。 If it is an object or array then your need to know that it is a reference and changes will affect the original variable as well. 如果它是一个对象或数组,那么您需要知道它是一个引用,并且更改也会影响原始变量。 And finally if it is a function then you have to be aware that you will loose it's context in the code example above. 最后,如果它是一个函数,那么您必须意识到您将在上面的代码示例中松开它的上下文

function foo() {}

var bar = foo; // Context is irrelevant.

function foo() {
  this.baz = 'foobar';
}

var bar = foo; // You must provide a context or `this` becomes `window`.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM