声明新变量或在函数中使用引用

Declaring new variables or using references in functions?

本文关键字:函数 引用 新变量 变量 声明      更新时间:2023-09-26

在为类定义方法时,是自己使用成员更好,还是将它们分配给新变量会更快?想象一下,例如在JavaScript中,以下方法:

square: function() {
    var x = this.x;
    x *= x;
    return x;
}

square: function() {
    this.x *= this.x;
    return this.x;
}

一般来说,速度的差异几乎总是可以忽略不计的,这意味着这是一个过早的优化,应该避免使用任何更易于维护的方法。

但是,在您的特定情况下,两种square方法之间的功能存在重大差异,如下所示。

var a = {
    x: 2,
    square: function() {
        var x = this.x;
        x *= x;
        return x;
    }
}
console.log('Result of a.square():', a.square()); //Output is 4
console.log('After square, a.x is:', a.x); //Output is 2
var b = {
    x: 2,
    square: function() {
        this.x *= this.x;
        return this.x;
    }
}
console.log('Result of b.square():', b.square()); //Output is 4
//The difference is here: b.x will be 4 while a.x is still 2
console.log('After square, b.x is:', b.x); //Output is 4

第一种square方法不会更新this.x,但第二种方法会更新。使用符合您意图的版本。在消除过早优化后,每种方法的简化版本如下。可维护性的收益是显而易见的。

第一版(不更新this.x(:

square: function() {
    return this.x * this.x;
}

第二版(this.x更新(:

square: function() {
    return this.x *= this.x;
}