JavaScript 函數++

JavaScript 函數++

1函數的參數類型

函數可以作爲參數進行傳遞。

function showMsg(name,age,gender,showTime){

// showTime = laoxieSay;

// showTime = function(){}

// showTime = '我看起來很年輕'

document.write('<p>我叫' + name + ', 今年' + age + '歲,' + gender + '</p>');

// 確定傳進來的參數爲function才執行

if(typeof showTime === 'function'){

showTime();

}

}

function laoxieSay(){

document.write('<strong>其實我還小</strong>');

}

showMsg('laoxie',18,'',laoxieSay);

showMsg('lemon',28,'',function(){

document.write('<strong>其實我不止28</strong>');

});

showMsg('laolan',32,'','我看起來很年輕');

 

上述案例中,下面的function可以作爲一個實參,寫入到手動執行的showMsg()中。

2 onload事件與獲取body元素

onload內容加載完成後執行;window.onload爲頁面所有內容(包括圖片、文件、音樂、視頻等)加載完成後 ;window.onload = function(){}; 內容加載完成後執行函數。

獲取body元素的背景顏色這個屬性,document.body.style.backgroundColor

3 return函數返回值

函數的返回值,運算(調用函數)後得到的值。

1 終止函數的執行,return後的代碼不會執行

2 return後如果有值,則把這個值返回到函數執行的地方如果函數沒有return,執行完後返回值undefined;如果return後沒有值,則得到undefined

function randomColor(){

var r = parseInt(Math.random()*256);

var g = parseInt(Math.random()*256);

var b = parseInt(Math.random()*256);

 

var color = 'rgb(' + r + ',' + g + ',' + b + ')';

 

// 函數返回值

return color;

}

則,此時background-color = randomColor();  background-color的值爲color

4函數中的this

函數中的this是一個關鍵字,表示當前對象,而當前對象是誰,取決於誰調用了這個函數

function getMsg(){

// * arguments

// * this

console.log(this);

}

// 手動立即執行

getMsg();//window

var btn = document.getElementById('btn');

// 事件觸發函數的執行

btn.onclick = getMsg;//button

// 獲取輸入框的內容

var username = document.getElementById('username');

 

username.onchange = function(){

// this === username

console.log(this.value);

}

5 函數遞歸

函數可以自己調用自己, 成爲函數的遞歸調用

遞歸調用的過程:

1 首先去找臨界值,即無需計算,獲得的值(一般是返回該值)

2找這一次和上一次的關係(一般從後往前找)

3假設當前函數已經可以使用,調用自身計算上一次的運行結果,再寫出這次的運行結果。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章