所以,我做了這段代碼來幫助我添加函數之前或之前的其他功能,但我想不出一個更好的方式來做到這一點,我不得不使用eval(),那是真的不是一個好習慣。起初,我試圖做一些事情:面向Javascript的東西
Function.prototype.append = function(fn){
eval("this = function(){ ("+this.toString()+").apply(this, arguments); fn.apply(this, arguments); }");
}
hello = function(){
console.log("hello world!");
}
hello(); // hello world!
hello.append(function(){
console.log("bye world!");
});
hello(); // hello world! bye world
但它沒有工作,因爲該功能不能改變自己。所以我這樣做:
Aspects = new Object();
Aspects.append = function(aspect, fn){
eval(aspect + " = function(){ ("+eval(aspect + '.toString()')+").apply(this, arguments); fn.apply(this, arguments); }");
}
Aspects.prepend = function(aspect, fn){
eval(aspect + " = function(){ fn.apply(this, arguments); ("+eval(aspect + '.toString()')+").apply(this, arguments); }");
}
hello = function(){
console.log("hello world!");
}
hello(); // hello world!
Aspects.append('hello', function(){
console.log("bye world!");
});
hello(); // hello world! bye world!
我不想與物體或任何工作,我只是想後還是
還要注意你的依靠'Function.prototype.toString'返回的東西理智,不會。 – Raynos