所以,我做了这段代码来帮助我添加函数之前或之前的其他功能,但我想不出一个更好的方式来做到这一点,我不得不使用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