“Closures are poor man's objects and vice versa” - What does this mean?

后端 未结 6 976
囚心锁ツ
囚心锁ツ 2020-11-28 02:48

Closures are poor man\'s objects and vice versa.

I have seen this statement at many places on the web (including SO) but I don\'t quite

6条回答
  •  广开言路
    2020-11-28 03:05

    The point is that closures and objects accomplish the same goal: encapsulation of data and/or functionality in a single, logical unit.

    For example, you might make a Python class that represents a dog like this:

    class Dog(object):
        def __init__(self):
            self.breed = "Beagle"
            self.height = 12
            self.weight = 15
            self.age = 1
        def feed(self, amount):
            self.weight += amount / 5.0
        def grow(self):
            self.weight += 2
            self.height += .25
        def bark(self):
            print "Bark!"
    

    And then I instantiate the class as an object

    >>> Shaggy = Dog()
    

    The Shaggy object has data and functionality built in. When I call Shaggy.feed(5), he gains a pound. That pound is stored in variable that's stored as an attribute of the object, which more or less means that it's in the objects internal scope.

    If I was coding some Javascript, I'd do something similar:

    var Shaggy = function() {
        var breed = "Beagle";
        var height = 12;
        var weight = 15;
        var age = 1;
        return {
            feed : function(){
                weight += amount / 5.0;
            },
            grow : function(){
                weight += 2;
                height += .25;
            },
            bark : function(){
                window.alert("Bark!");
            },
            stats : function(){
                window.alert(breed "," height "," weight "," age);
            }
        }
    }();
    

    Here, instead of creating a scope within an object, I've created a scope within a function and then called that function. The function returns a JavaScript object composed of some functions. Because those functions access data that was allocated in the local scope, the memory isn't reclaimed, allowing you to continue to use them through the interface provided by the closure.

提交回复
热议问题