简体   繁体   中英

Javascript - Use local var or this?

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; 
    }
}

There's probably no meaningful difference between self.x and this.x . What might make a difference is

  var x = this.x, y = this.y;

  // massive amounts of computation involving x and y

Such 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 is the standard way to access x and y . You'll get no improvements from caching this to a local var—if anything, you're wasting space by declaring self in the first place.

The only possible risk you'd see is with something like this:

var f = new foo();
var stupid = f.addValues;
stupid(); // whoops - this is suddenly the global object, 
          // and your method is broken.

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 to Foo

In this example, assigning this to self should not make any difference. JavaScript does not assign objects by value, but rather by reference, meaning that self and this both then point to the same object. You gain nothing by doing so.

foo.prototype = {
    addValue:  function (){
       // self and this point to the same object! 
       var self = this;
        return self.x + self.y; 
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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