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~
女神的闺蜜爱上我
女神的闺蜜爱上我 2017-07-05 11:00:45
0
3
842
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? ~

女神的闺蜜爱上我
女神的闺蜜爱上我

reply all(3)
三叔

Transfer, global variables are rarely used

淡淡烟草味

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!

曾经蜡笔没有小新

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?

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template