简体   繁体   中英

many local variables declaration vs one global?

i'm just new javascript biginner, If i need to reuse many times (lets say 20 times) the same variable, from a performance point of view, should i declare it one time as global , or declare it many times in each function context in local scope ( as i heard about ) ?

whats case bellow is better ?

caseA :

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

Wrap case A inside a closure

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

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

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

now nothing is in the global scope but you only access the DOM once.

The case A must be the best, or if you like object oriented programming you can do :

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();

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