ExtJS 3: Two ways of creating custom class: what's the difference?

前端 未结 2 2202
执念已碎
执念已碎 2021-02-20 00:37

I\'m trying to learn ExtJS and object-oriented JavaScript in general. I\'ve seen people defining classes in custom namespaces in a couple of ways. What\'s the difference between

2条回答
  •  感情败类
    2021-02-20 01:11

    The following are practically equivalent:

    var Car = Ext.extend(Object, {
       //...
    });
    
    myapp.cars.Car = Car;
    

    ... and:

    myapp.cars.Car = Ext.extend(Object, {
       //...
    });
    

    In the first example you'd be using a temporary variable to hold a reference to the newly created object, which is then copied to myapp.cars.Car (the reference is copied, not the object). In the second example you'd be assigning the reference to the object directly to myapp.cars.Car.

    The reason your first example was enclosed in the self-invoking anonymous function (function(){ })() is to limit the scope of that temporary variable. That is generally done in order not to pollute the global namespace with that Car variable. If there was an other Car variable defined elsewhere, it would not conflict with this one. Example:

    var Car = "My Nice Car";
    
    (function(){
        var Car = Ext.extend(Object, {
           //...
        });
    
        myapp.cars.Car = Car;
    })();
    
    alert(Car); // Still "My Nice Car"
                // No conflict with the `Car` variable in the self invoking function.
    

提交回复
热议问题