#12003/3/11 12:50:02
Fiddling With The Function Prototype
I came across this interesting thread on Flashforum.de (beware it's german). Florian Krüsch and Ralf Bokelberg are exploring the extension of the function prototype.
It starts with the basic idea that instead of an object or a variable you can as well return an anonymus function as the result of a function call:
function addTag(tag) {
var stag='<'+tag+'>';
var etag=''+tag+'>';
return function(x) {
return stag+x+etag;
}
}
trace(addTag("b")("hello world"))
returns: hello world
========
function addTag(tag,x) {
var stag='<'+tag+'>';
var etag=''+tag+'>';
return( stag+x+etag)
}
trace(addTag("b","hello world"))
这样好像容易懂。
========
But now you can also extend the Function object itself which will add "helper" functions to all other functions:
Function.prototype.loop=function(x) {
var f=this;
return function() {
for (var i=0; if.apply(f,arguments);
}
}
}
function test(t){
trace(t)
}
test.loop(5)("hello world")
returns:
hello world
hello world
hello world
hello world
hello world
There are some nice things you can do with this method:
Function.prototype.executeLater = function() {
var func = this;
var timeToWait=arguments.shift();
var args=arguments;
var intervalId = setInterval(function () {
func.apply(f,args);
clearInterval(intervalId);
}, timeToWait);
};
Function.prototype.setDelay = function(timeToWait) {
var func = this;
return function() {
var args=arguments;
var intervalId = setInterval(function () {
func.apply(f,args);
clearInterval(intervalId);
}, timeToWait);
}
};
function test(){
trace("test " + arguments);
}
test.executeLater(100,"flory", "was", "here");
test.setDelay(1000)("flory","was","here","again");
testDelayed1000=test.setDelay(1000);
// now testDelayed has stored the delay and will always wait 1000ms
// before it calls test
testDelayed1000("flory","was","here","yet again");
编辑历史:[这消息被s22编辑过(编辑时间2003-03-17 09:38:14)]