![](/img/trans.png)
[英]Why does JavaScript take a variable amount of time to run the same function?
[英]Why does javascript function run each time?
為什么以下javascript代碼以這種方式運行?
var plusOne = function(num){
return num+1;
};
var total=plusOne(1);
console.log(total);
var total2=plusOne(3);
console.log(total2);
如果我是對的
var total=plusOne(1);
console.log(total);
向變量total
和變量plusOne
返回值2
,然后將其記錄到控制台“ 2”,但是如果plusOne
的值現在為2
,為什么
var total2=plusOne(3);
console.log(total2);
返回值為4,因為它不是實際執行的實際代碼
var total2=2(3);
console.log(total2);
沒有。
JavaScript無法以這種方式工作。 實際上,我無法想到以這種方式起作用的任何編程語言。 plusOne
只是該函數的指針。
當您執行第一行時,值2
被存儲在total
,但是plusOne
不會發生任何變化。
當您執行第二行時,Javascript不會在乎該函數是否稱為eariler。
plusOne
是對該函數的引用。 它僅引用函數,不存儲其返回的值。 每次調用plusOne
引用的plusOne
都獨立於對該函數的先前調用。
該代碼在功能上等效於:
function plusOne(num){
return num+1;
};
var total=plusOne(1);
console.log(total);
var total2=plusOne(3);
console.log(total2);
plusOne甚至沒有分配第一個計算的值。 plusOne在那里或不在那里沒有任何意義。 total分配了值2。因此,第一次打印將為2,第二次打印將為4,因為您在下一個函數調用期間傳入了3。
plusOne是函數類型,而不是數字,而總數是一個數字,因此plusOne並不保留對數字的引用,而是對函數本身的引用。
http://tech.deepumohan.com/2013/07/javascript-pass-function-as-parameter.html
您已經聲明了一個名為plusOne()的函數,該函數具有一個參數:即調用該函數時要提供的數字。 盡管plusOne()被分配為變量,但它指向內存中的存儲桶,該存儲桶將返回您作為參數傳遞的數字的1+。 它不會存儲對函數參數的先前調用。
有多種方法可以在javascript中聲明函數:請閱讀以供參考
因此,這里有一個示例,說明在某些更改期間為什么以及發生了什么。 單擊此JSFiddle鏈接,然后單擊“運行”並閱讀注釋。 http://jsfiddle.net/pGcrL/
以下是您可以在鏈接中找到的js小提琴代碼。
var plusOne = function(num){
return num+1;
};
$('#tempconsoleoutput').html(typeof plusOne);
//Since plusOne is a function you can not make it a variable.
//You must say something like plusOne = plusOne(1);
plusOne = plusOne(1);
$('#tempconsoleoutput2').html(typeof plusOne);
var total=plusOne(1);//With the plusOne now being a number
//you will find that there is an exception in your console now.
console.log(total);
var total2=plusOne(3);
console.log(total2);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.