javascript面向对象编程(一)
javascript曾一度被认为是玩具型的语言,因为它太容易上手,而且,javascript曾一度担任为web站点“打杂”的职责。直到Ajax的兴起,这个在幕后默默无闻多年的语言才崭露头角,它的灵活性赋予了开发者无穷的想象力。javascript不提供传统的OOP方式,但是仍然可以轻松的实现OOP。
[强大的原型prototype]
这是一段来自《javascript design patterns》的代码:
JavaScript:
-
/* Start and stop animations using functions. */
-
-
function startAnimation() {
-
...
-
}
-
-
function stopAnimation() {
-
...
-
}
-
-
-
-
/* Anim class. */
-
-
var Anim = function() {
-
...
-
};
-
Anim.prototype.start = function() {
-
...
-
};
-
Anim.prototype.stop = function() {
-
...
-
};
-
-
/* Usage. */
-
-
var myAnim = new Anim();
-
myAnim.start();
-
...
-
myAnim.stop();
-
-
-
-
/* Anim class, with a slightly different syntax for declaring methods. */
-
-
var Anim = function() {
-
...
-
};
-
Anim.prototype = {
-
start: function() {
-
...
-
},
-
stop: function() {
-
...
-
}
-
};
-
-
-
-
/* Add a method to the Function class that can be used to declare methods. */
-
-
Function.prototype.method = function(name, fn) {
-
this.prototype[name] = fn;
-
};
-
-
/* Anim class, with methods created using a convenience method. */
-
-
var Anim = function() {
-
...
-
};
-
Anim.method('start', function() {
-
...
-
});
-
Anim.method('stop', function() {
-
...
-
});
-
-
-
-
/* This version allows the calls to be chained. */
-
-
Function.prototype.method = function(name, fn) {
-
this.prototype[name] = fn;
-
return this;
-
};
-
-
/* Anim class, with methods created using a convenience method and chaining. */
-
-
var Anim = function() {
-
...
-
};
-
Anim.
-
method('start', function() {
-
...
-
}).
-
method('stop', function() {
-
...
-
});
这段代码充分展示了javascript的OO能力,相信你也早就见识过,毕竟这已经不是新闻了。见过的一篇比较好的关于prototype原型的文章:不是原型继承那么简单!!prototype的深度探索,推荐大家看看。
呵呵,我要学javascript的化,就看你的教程了,兄弟你可要快点写啊!!
呵呵,我写这个主要是为了梳理自己的思路,想到哪就写到哪,而且肯定漏洞百出。还等着你来指正呢!