许多局部变量声明与一个全局?

时间:2014-10-15 15:57:54

标签: javascript performance global-variables scope local

我只是新的javascript biginner, 从性能的角度来看,如果我需要重复使用多次(比方说20次)相同的变量, 我应该将其声明为全局一次,还是在本地范围内的每个函数上下文中多次声明(如我所知)?

什么情况比较好?

案例A:

var myvar = document.getElementById('case'); //global

function one(){
myvar.innerHTML = 'newb';
...
}
function two(){
myvar.value = '3';
...
}

caseB:

function one(){
var myvar = document.getElementById('case'); //local
myvar.innerHTML = 'newb';
...
}
function two(){
var myvar = document.getElementById('case'); //lobal 
myvar.value = '3';
...
}

caseC:

var myvar = document.getElementById('case'); //global

function one(){
var myvar = document.getElementById('case'); //local
myvar.innerHTML = 'newb';
...
}
function two(){
var myvar = document.getElementById('case'); //lobal 
myvar.value = '3';
...
}

thx for advises,
GUI

2 个答案:

答案 0 :(得分:1)

在封闭内包裹案例A

(function() {
  var myvar = document.getElementById('case');

  function one(){
    myvar.innerHTML = 'newb';
    ...
  }

  function two(){
    myvar.value = '3';
    ...
  }
})()

现在没有任何内容属于全局范围,但您只能访问DOM一次。

答案 1 :(得分:1)

案例A必须是最好的,或者如果你喜欢面向对象的编程,你可以这样做:

function MyClass() {
    this.element = document.getElementById('case');

    this.one = function() {
        this.element.innerHTML = 'newb';
    }
    this.two = function() {
        this.element.value = '3';
    }

    return this;
}

var myCls = new MyClass();
myCls.one();
myCls.two();