好吧,先從讓我們看看一些代碼:確定封裝的JavaScript函數的值參數
<html>
<body>
<script type="text/javascript">
function logFunction(fn) {
console.log(fn.prototype);
console.log(fn);
console.log(fn(4));
}
var num = 5;
var add5 = function(x) { return x + 5 };
var addNum = function(x) { return x + num };
var adder = function(y) { return function(x) { return x + y } };
logFunction(add5);
logFunction(addNum);
logFunction(adder(5));
</script>
</body>
</html>
執行時,它會返回以下結果:
Object
constructor: function (x) { return x + 5 }
__proto__: Object
function (x) { return x + 5 }
9
Object
constructor: function (x) { return x + num }
__proto__: Object
function (x) { return x + num }
9
Object
constructor: function (x) { return x + y }
__proto__: Object
function (x) { return x + y }
9
雖然它會很容易在第一種情況下,看到x將被添加的值是5,我似乎無法想出一種方法來對另外兩種情況做同樣的處理。
我的問題是這樣的:有沒有一種方法可以確定在最後兩個例子中x被添加到的值的值,只有函數引用和變量被調用的知識(「num」 「y」等)?
編輯:
好吧,我可以看到,發現這些值是不可能的。唯一的辦法是,如果我可以訪問匿名函數的「參數」屬性,但可惜,這也是不可能的。我的工作是要求一個Function類型的Object作爲參數。這個問題還存在一些問題,我可以在下面的新代碼中看到,但這應該適用於我的情況。感謝大家!
<html>
<body>
<script type="text/javascript">
function logFunction(fn) {
console.log(fn.prototype);
console.log(fn);
console.log(fn(4));
console.log("");
console.log("");
}
var num = 5;
var addNumFunc = new Function("x", "return x + " + num);
var whereNumFunc = new Function("x", "return x >= " + num * num);
var adderFunc = new Function("y", "return function(x) { return x + y }");
var adderFuncFunc = new Function("y", "return new Function(\"x\", \"return x + \" + y)");
logFunction(addNumFunc);
logFunction(whereNumFunc);
logFunction(adderFunc);
logFunction(adderFunc(5));
logFunction(adderFuncFunc);
logFunction(adderFuncFunc(5));
</script>
</body>
</html>
將返回:
anonymous
function anonymous(x) {
return x + 5
}
9
anonymous
function anonymous(x) {
return x >= 25
}
false
anonymous
function anonymous(y) {
return function(x) { return x + y }
}
function (x) { return x + y }
Object
function (x) { return x + y }
9
anonymous
function anonymous(y) {
return new Function("x", "return x + " + y)
}
function anonymous(x) {
return x + 4
}
anonymous
function anonymous(x) {
return x + 5
}
是的,有一種方法:寫一個Javascript解釋器。 – Pointy 2010-10-06 13:28:54