prototype.jsソース分析

Enumerable近辺を理解するために

  • bindを把握する。prototype.jsを使わずに必要部分を抜き出してみる。
  • 以下をコピペで動作します。(そのはず;)
<script>
Object.extend = function(destination, source){
	for(var p in source){
		destination[p] = source[p];
	}
	return destination;
}
Object.extend(Function.prototype, {
	bind: function() {
		if (arguments.length < 2 && arguments[0] === undefined) return this;
	    var __method = this, args = $A(arguments), object = args.shift();
	    return function() {
	      return __method.apply(object, args.concat($A(arguments)));
	    }
	}
});
function $A(iterable) {
  if (!iterable) return [];
  if (iterable.toArray) return iterable.toArray();
  var length = iterable.length, results = new Array(length);
  while (length--) results[length] = iterable[length];
  return results;
}
//*------------------------------------------------*//
document.write("<pre>");
for(p in Function.prototype){
	document.write(p + " : " + Function.prototype[p] + "<hr>");
}

var Nabe = function(dasi){
	this.dasi = dasi;
	this.say = function(){
		alert(this.dasi);
	}
}
var fuguchiri = new Nabe('konbu');
alert(typeof fuguchiri.say);
setTimeout(fuguchiri.say, 1000);
setTimeout(fuguchiri.say.bind(fuguchiri), 1000);
</script>