Home  >  Q&A  >  body text

javascript - If a method needs to use external data, should you choose to pass it as a parameter or save the data as a global variable relative to the current scope~

var test = {
    init: function () {
        var data = $rootScope.test;
        
        if(data) {
            ……
            this.method(data);
        } 
    },
    
    method: function (data) {
        console.log(data);
    }
};

still

var test = {
    data: $rootScope.test,
    
    init: function () {
        if(this.data) {
            ……
            this.method();
        } 
    },
    
    method: function () {
        console.log(this.data);
    }
};

Which method is the best practice

What to do if there are too many levels to be passed in the first method. For example, it starts with init calling the method. After passing it, there are method[n] execution sequences, such as init -> method -> method2 -> method3. Is it passed on level by level...

There are also two methods, which one has higher performance? The second method is equivalent to getting the properties of the object every time. It seems that the performance of directly passing parameters will be worse? ~

女神的闺蜜爱上我女神的闺蜜爱上我2663 days ago808

reply all(3)I'll reply

  • 三叔

    三叔2017-07-05 11:02:45

    Transfer, global variables are rarely used

    reply
    0
  • 淡淡烟草味

    淡淡烟草味2017-07-05 11:02:45

    Global variables are not counted in your example!

    Hang on the properties of the object and will not affect the use of variables inside the method! It won’t pollute the scope either!

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-07-05 11:02:45

    What you implement here is not a global variable, it is just attached to the properties of the object. Why is it necessary to declare a variable here? I have not seen you actually operate this data. If you just want to quote it, then directly Wouldn’t it be better to use $rootScope.test?

    reply
    0
  • Cancelreply