ExtJS 3:创建自定义类的两种方法:有什么区别?
我正在尝试总体学习 ExtJS 和面向对象的 JavaScript。我见过人们通过多种方式在自定义命名空间中定义类。这两种方法有什么区别?
方法1
Ext.ns('myapp.cars');
(function(){
var Car = Ext.extend(Object, {
//...
})
myapp.cars.Car = Car;
})()
方法2
Ext.ns('myapp.cars');
myapp.cars.Car = Ext.extend(Object, {
//...
});
方法2更容易阅读,需要的代码更少;有什么理由方法1更好吗?谢谢!
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 these two methods?
Method 1
Ext.ns('myapp.cars');
(function(){
var Car = Ext.extend(Object, {
//...
})
myapp.cars.Car = Car;
})()
Method 2
Ext.ns('myapp.cars');
myapp.cars.Car = Ext.extend(Object, {
//...
});
Method 2 is easier to read and requires less code; is there any reason Method 1 is better? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
基本上是一样的,只是你可以在第一个方法的自执行函数中使用私有变量,而你只能在第二个方法中定义全局变量。
例如:
因此,如果您使用稍后不会使用的大量变量,则第一种方法非常有用。
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:
So, the first method is quite useful if you work with a bunge of variables that you won't use later on.
以下内容实际上是等效的:
...并且:
在第一个示例中,您将使用临时变量来保存对新创建的对象的引用,然后将其复制到
myapp.cars.Car
(复制的是引用,而不是对象)。在第二个示例中,您将对对象的引用直接分配给myapp.cars.Car
。您的第一个示例包含在自调用匿名函数
(function(){ })()
中的原因是为了限制该临时变量的范围。这样做通常是为了不让Car
变量污染全局命名空间。如果在其他地方定义了其他Car
变量,则它不会与此变量冲突。例子:The following are practically equivalent:
... and:
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 tomyapp.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 thatCar
variable. If there was an otherCar
variable defined elsewhere, it would not conflict with this one. Example: