前面有一篇日誌是寫道有關JS變數的,這裡還寫JS變數。看例子:
<script type="text/javascript">var str='abcde'; var obj=new String(str);function newToString(){return 'Hello world!';}function func(val){val.toString=newToString;}//樣本1:傳入值func(str);alert(str);//樣本2:傳入引用func(obj);alert(obj);</script>
Tips:func(xxx);是修改值的。
這樣如果難看一點,可以看看之前的那個差不多的例子:
var a = 3.14; // Declare and initialize a variablevar b = a; // Copy the variable's value to a new variablea = 4; // Modify the value of the original variablealert(b) // Displays 3.14; the copy has not changedvar a = [1,2,3]; // Initialize a variable to refer to an arrayvar b = a; // Copy that reference into a new variablea[0] = 99; // Modify the array using the original referencealert(b); // Display the changed array [99,2,3] using the new reference
變數聲明
變數聲明有兩種方法:顯式和隱式。
顯式一般是指使用Var聲明,隱式(即用即聲明)
//聲明變數var str='abc';//聲明函數function foo(){ str='abc';}//南明異常對象extry{ //...}catch(ex){ //...}