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

老子叫甜甜 提交于 2019-12-04 00:59:54

It's basically the same, except that you could use private variables in the self-exectuing function of the first method, while you can only define global variables in the second one.

For example:

Ext.ns('myapp.cars');
(function(){

    var carInfo = {
      goodEngine: true
    };

    var Car = Ext.extend(Object, {
       info: carInfo
    });

    myapp.cars.Car = Car;
})()

// carInfo is undefined here, so this will give an error
alert( carInfo.goodEngine );

So, the first method is quite useful if you work with a bunge of variables that you won't use later on.

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.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!