继承
我使用基于ExtJS 3 的notation for inheritance,我发现它非常接近于在Java 中模拟经典继承。它基本上运行如下:
// Create an 'Animal' class by extending
// the 'Object' class with our magic method
var Animal = Object.extend(Object, {
move : function() {alert('moving...');}
});
// Create a 'Dog' class that extends 'Animal'
var Dog = Object.extend(Animal, {
bark : function() {alert('woof');}
});
// Instantiate Lassie
var lassie = new Dog();
// She can move and bark!
lassie.move();
lassie.bark();
命名空间
我也同意 Eric Miraglia 坚持使用命名空间的观点,因此上面的代码应该在窗口对象之外的自己的上下文中运行,如果您希望您的代码作为在浏览器窗口。
这意味着访问窗口对象的唯一方法是通过您自己的命名空间/模块对象:
// Create a namespace / module for your project
window.MyModule = {};
// Commence scope to prevent littering
// the window object with unwanted variables
(function() {
var Animal = window.MyModule.Animal = Object.extend(Object, {
move: function() {alert('moving...');}
});
// .. more code
})();
接口
您还可以利用更先进的 OOP 构造(例如接口)来增强您的应用程序设计。 My approach to these 是对Function.prototype 的增强,以便获得符合这些方面的符号:
var Dog = Object.extend(Animal, {
bark: function() {
alert('woof');
}
// more methods ..
}).implement(Mammal, Carnivore);
OO 模式
至于 Java 意义上的“模式”,我只发现 Singleton pattern(非常适合缓存)和 Observer pattern 用于事件驱动的功能,例如在用户单击时分配一些操作按钮。
使用观察者模式的一个例子是:
// Instantiate object
var lassie = new Animal('Lassie');
// Register listener
lassie.on('eat', function(food) {
this.food += food;
});
// Feed lassie by triggering listener
$('#feeding-button').click(function() {
var food = prompt('How many food units should we give lassie?');
lassie.trigger('eat', [food]);
alert('Lassie has already eaten ' + lassie.food + ' units');
});
这只是我的 OO JS 包中的一些技巧,希望它们对你有用。
如果您打算走这条路,我建议您阅读 Douglas Crockfords Javascript: the Good Parts。这是一本很棒的书。