關於 byval 與 byref 的區別分析總結_javascript技巧

來源:互聯網
上載者:User
二者區別:
byval 傳遞數值,實參和形參分處不同的記憶體單元,互不干擾! 
byref 傳遞地址,實參和形參佔用相同的記憶體單元,形參變則實參變!!!!!!
通俗理解:
byval 一去不複返 
byref 進去再出來,可能被更新!
在JavaScript中:
Boolean,Number,String型的參數是按值傳遞的 ==> 相當於VBS中的ByVal;
而Object型的參數(包括JS對象,Array對象,Function對象等),是按引用傳遞 ==> 相當於VBS中的ByRef
複製代碼 代碼如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" lang="zh-CN"> 
<head> 
<title> 函數傳值測試 </title> 
<meta http-equiv="content-type" content="text/html; charset=utf-8" /> 
<meta name="author" content="楓岩,CNLEI" /> 
<meta name="copyright" content="cnlei.y.l@gmail.com , http://www.cnlei.com" /> 
</head> 
<body> 
<script type="text/javascript"> 
<!-- 
function Num(n){n=n*2;}//Number型的參數,按值傳遞的 ==> 相當於VBS中的ByVal; 
function Obj(){} 
Obj.prototype.show = function(o){ //JS對象,是按引用傳遞 ==> 相當於VBS中的ByRef 
  o.toString = function(){ 
    return("{id:"+this.id+",desc:"+this.desc+"}"); 
  } 
} 
function Func(f){ //Function對象,是按引用傳遞 ==> 相當於VBS中的ByRef 
  f.show = function(o){ 
    o.toString = function(){ 
      return("{id:"+this.id+",desc:"+this.desc+",toString:function(){} }"); 
    } 
  } 
} 

var N; 
N=1; 
alert(N); 
Num(N); 
alert(N); 

var O; 
O = { 
  id:"001", 
  desc:"編號說明", 
  toString: function (){ 
    return null; 
  } 
}; 
var F = new Obj(); 
var F2 = new Obj(); 
alert(O.id+"\n"+O.toString()); 
F.show(O); 
alert(O.id+"\n"+O.toString()); 
Func(F); 
F.show(O); 
alert(O.id+"\n"+O.toString()); 
//--> 
</script> 
</body> 
</html> 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.