programing tip

JS 객체를 정의하는이 방법에는 어떤 목적이 있습니까?

itbloger 2020. 9. 12. 09:15
반응형

JS 객체를 정의하는이 방법에는 어떤 목적이 있습니까?


일부 레거시 코드를 유지하고 있는데 객체를 정의하는 데 다음 패턴이 사용되는 것을 발견했습니다.

var MyObject = {};

(function (root) {

    root.myFunction = function (foo) {
        //do something
    };

})(MyObject);

이것에 어떤 목적이 있습니까? 다음을 수행하는 것과 동일합니까?

var MyObject = {

    myFunction : function (foo) {
        //do something
    };

};

나는 전체 코드베이스를 내 취향에 맞게 리팩토링하기위한 신성한 탐구에 착수 할 예정이 아니지만, 객체를 정의하는 로터리 방식의 이유를 정말로 이해하고 싶습니다.

감사!


모듈 패턴 http://toddmotto.com/mastering-the-module-pattern/ 이라고합니다.

주된 이유는 진정한 개인 메서드와 변수를 만드는 것입니다. 귀하의 경우에는 구현 세부 정보를 숨기지 않기 때문에 의미가 없습니다.

다음은 모듈 패턴을 사용하는 것이 타당한 예입니다.

var MyNameSpace = {};

(function(ns){
    // The value variable is hidden from the outside world
    var value = 0;

    // So is this function
    function adder(num) {
       return num + 1;
    }

    ns.getNext = function () {
       return value = adder(value);
    }
})(MyNameSpace);

var id = MyNameSpace.getNext(); // 1
var otherId = MyNameSpace.getNext(); // 2
var otherId = MyNameSpace.getNext(); // 3

당신은 그냥 직선 객체를 사용하는 경우 반면 addervalue공공 될 것

var MyNameSpace = {
    value: 0,
    adder: function(num) {
       return num + 1;
    },
    getNext: function() {
       return this.value = this.adder(this.value);
    }
}

그리고 당신은 다음과 같은 일을함으로써 그것을 부술 수 있습니다.

MyNameSpace.getNext(); // 1
MyNameSpace.value = 0;
MyNameSpace.getNext(); // 1 again
delete MyNameSpace.adder;
MyNameSpace.getNext(); // error undefined is not a function

하지만 모듈 버전으로

MyNameSpace.getNext(); // 1
 // Is not affecting the internal value, it's creating a new property
MyNameSpace.value = 0;
MyNameSpace.getNext(); // 2, yessss
// Is not deleting anything
delete MyNameSpace.adder;
MyNameSpace.getNext(); // no problemo, outputs 3

목적은 클로저 내에서 함수의 접근성 을 제한 하여 다른 스크립트 가 코드를 실행 하지 못하도록 하는 것입니다. 을 주위에 포장하여 폐쇄 하면 다시 정의하는 범위 내 모든 코드 실행을 폐쇄 하고 효과적으로 개인 범위를 생성. 자세한 내용은이 문서를 참조하십시오.

http://lupomontero.com/using-javascript-closures-to-create-private-scopes/

기사에서 :

One of the best known problems in JavaScript is its dependance on a global scope, which basically means that any variables you declare outside of a function live in the same name space: the ominous window object. Because of the nature of web pages, many scripts from different sources can (and will) run on the same page sharing a common global scope and this can be a really really bad thing as it can lead to name collisions (variables with the same names being overwritten) and security issues. To minimise the problem we can use JavaScript’s powerful closures to create private scopes where we can be sure our variables are invisible to other scripts on the page.



Code:

var MyObject = {};

(function (root) {
    function myPrivateFunction() {
       return "I can only be called from within the closure";
    }

    root.myFunction = function (foo) {
        //do something
    };    

    myPrivateFunction(); // returns "I can only be called from within the closure"

})(MyObject);


myPrivateFunction(); // throws error - undefined is not a function

advantages:

  1. maintains variables in private scope.

  2. you can extend the functionality of the existing object.

  3. performance is increased.

i think the above three simple points are just enough to follow those rules. And to keep it simple its nothing but writing inner functions.


In the particular case that you show, there is no meaningful difference, in terms of functionality or visibility.

It's likely that the original coder adopted this approach as a sort of template allowing him to define private variables that could be used in the definition of things like myFunction:

var MyObject = {};
(function(root) {
    var seconds_per_day = 24 * 60 * 60;   // <-- private variable
    root.myFunction = function(foo) {
        return seconds_per_day;
    };
})(MyObject);

This avoids calculating seconds_per_day each time the function is called, while also keeping it from polluting the global scope.

However, there's nothing essentially different from that and just saying

var MyObject = function() {
    var seconds_per_day = 24 * 60 * 60;
    return {
        myFunction: function(foo) {
            return seconds_per_day;
        }
    };
}();

The original coder may have preferred to be able to add functions to the object using the declarative syntax of root.myFunction = function, rather than the object/property syntax of myFunction: function. But that difference is mainly a matter of preference.

However, the structure taken by the original coder has the advantage that properties/methods can be easily added elsewhere in the code:

var MyObject = {};
(function(root) {
    var seconds_per_day = 24 * 60 * 60;
    root.myFunction = function(foo) {
        return seconds_per_day;
    };
})(MyObject);

(function(root) {
    var another_private_variable = Math.pi;
    root.myFunction2 = function(bar) { };
})(MyObject);

Bottom line, there is no need to adopt this approach if you don't need to, but there is also no need to change it, since it works perfectly well and actually has some advantages.


  1. First pattern can be used as a module which takes an object and returns that object with some modifications. In other words, you can define such modules as follows.

    var module = function (root) {
        root.myFunction = function (foo) {
            //do something
        };
    }
    

    And use it like:

    var obj = {};
    module(obj);
    

    So an advantage could be the re-usability of this module for later uses.


  1. In the first pattern, you can define a private scope to store your private stuff such as private properties and methods. For example, consider this snippet:

    (function (root) {
    
        // A private property
        var factor = 3;
    
        root.multiply = function (foo) {
            return foo * factor;
        };
    })(MyObject);
    

  1. This pattern can be used to add a method or property to all types of objects such as arrays, object literals, functions.

    function sum(a, b) {
        return a + b;
    }
    
    (function (root) {
        // A private property
        var factor = 3;
        root.multiply = function (foo) {
            return foo * factor;
        };
    })(sum);
    
    console.log(sum(1, 2)); // 3
    console.log(sum.multiply(4)); // 12
    

In my opinion the main advantage could be the second one (creating a private scope)


This pattern provides a scope in which you can define helper functions that are not visible in the global scope:

(function (root) {

    function doFoo() { ... };

    root.myFunction = function (foo) {
        //do something
        doFoo();
        //do something else
    };

})(MyObject);

doFoo is local to the anonymous function, it can't be referenced from outside.

참고URL : https://stackoverflow.com/questions/26788397/does-this-way-of-defining-js-objects-have-any-purpose

반응형