Prototype.js や MochiKit や jQuery や dojo
こういう便利なライブラリがたくさん出てきてとても便利になりました。
でもそのライブラリ本当に必要?
たしかに、グループワーキングを行うにはこれらのライブラリは必須だと思います。
でも、ちょいスクリプトを作るのに .bind(this) や $ や each や Event.observe が必要でしょうか。
いささかオーバスペックな気がします。
実際に「このツール Prototype.js 必須かよ。こっちは MochiKit で作ってるのにぃ」とかってことも多々あります。
あれを使うためにあれとこれを読み込んで、これを使うためにこれも必要だな。こんな感じだとサイトはどんどん重いものになってしまします。。。orz
そこで、原点回帰です。
ちょっとしたツールでライブラリ使うのはやめようよ!何も使わなくても JavaScript は楽しく書けるよ! script タグ一個でいろいろ出来るよ!
それ、ライブラリじゃなくてもできるよ!
しかも
FireBug のコンソールやアドレスバー*1で他サイトをいじりまくれますよ!ブックマークも GreaseMonkey も作りまくり!
どんなライブラリを読み込んでいようがいまいが、こっちは「普通の JavaScript」が書けるんだからね!
それでは Prototype.js を例に、普通化していきましょう
$
$('id');document.getElementById('id');ちょwwww本末転倒w
$A
var args = $A(arguments);
args.push('hoge');
args.shift();Array.prototype.push.apply(arguments, 'hoge'); Array.prototype.shift.apply(arguments);
bind
this.method1.bind(this); this.method2.bind(this, a, b);
var self = this;
function() { self.method1() };
function() {
Array.prototype.unshift.apply(arguments, a, b);
self.method2.apply(self, arguments);
};
bindAsEventListener
this.method1.bindAsEbentListener(this);
var self = this;
function(event) { self.method1(event || window.event) };
Event.observe
Event.observe('load', function() {alert('Loaded')});window.onload = function() {alert('Loaded')};
// OR
var handler = function() {alert('Loaded')};
try { window.addEventListener('load', handler) }
catch(e) {window.attachEvent('onload', handler) }
Event.pointerX Event.pointerY
move(Event.pointerX(event), Event.pointerY(event));
var html = document.documentElement, body = document.body;
move(
event.pageX || event.clientX + (html.scrollLeft || body.scrollLeft),
event.pageY || event.clientY + (html.scrollTop || body.scrollTop)
);
Event.stop
Event.stop(event);
(event.preventDefault||function(){
event.returnValue = false;
event.cancelBubble = true
})();
(event.stopPropagation||function(){})();
Class.create
var Hoge = Class.create;
Hoge.prototype = {
initialize: function() {
alert('Created');
}
};(window.Hoge = function() {this.initialize.apply(this, arguments)}).prototype = {
initialize: function() {
alert('Created');
}
}
Object.extend
var SubClass = Class.create;
Object.extend(SubClass.prototype, SuperClass.prototype);
Object.extend(SubClass.prototype, {
....
});(window.SubClass = function() {this.initialize.apply(this, arguments}).prototype = new SuperClass();
(function() {
var prototype = {
...
};
for(var n in prototype) SubClass.prototype[n] = prototype[n];
})();
each 系
['hoge', 'fuga'].each(function(e){alert(e)});for(var array = ['hoge', 'fuga'], i = 0, len = array.length; i < len; i ++) { alert(array[i]); }
このくらい出来れば充分じゃないですか??
読みにくいですか^^;?
ちょいスクリプトなら多少読みにくくても保守できますよ ^^
書きにくいですか^^;?
手が慣れますよ ^^
*1: javascript:(function(){})()