简体   繁体   English

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

[英]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 ) ? 我只是新的javascript专家,如果我需要重用很多次(比如说20次),那么从性能的角度来看,我应该将其声明为global一次,还是在每个函数上下文中声明多次?在当地(我听说)?

whats case bellow is better ? 什么情况下更好?

caseA : 案例A:

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

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

caseB : caseB:

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

caseC : 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 gui

Wrap case A inside a closure 将箱子A包裹在一个封闭物中

(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. 现在,全局范围内没有任何东西,但是您只能访问DOM一次。

The case A must be the best, or if you like object oriented programming you can do : 情况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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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