Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write methods without so many "this."?

Tags:

javascript

Are there ways to avoid using this. before each member in the method body?

JavaScript is amazing in many ways, but one thing that makes it hard to read is that you must use this. before every member:

TList.on_key = function(key) {
    if (key == 116) {
        this.sid++;
        if (this.sid > this.items.length - 1) this.sid = this.items.length - 1
        if (this.sid >= this.d + (this.h * this.columns)) this.d++
    }

Would be much easier to read without all those this. :

TList.on_key = function(key) {
    if (key == 116) {
        sid++;
        if (sid > items.length - 1) sid = items.length - 1
        if (sid >= d + (h * columns)) d++
    }
like image 455
exebook Avatar asked Oct 02 '22 12:10

exebook


1 Answers

Yes you can by using the "controversial" with statement as long as you're not in "strict mode", where it's prohibited.

TList.on_key = function(key) {
    with(this) {
        if (key == 116) {
            sid++;
            if (sid > items.length - 1) sid = items.length - 1
            if (sid >= d + (h * columns)) d++
        }
    }
}

Be sure to fully learn about it before using it though, as its semantics can catch people off guard.

like image 65
cookie monster Avatar answered Oct 05 '22 05:10

cookie monster