您现在的位置:首页 >> 前端 >> 内容

javascript函数++

时间:2017/8/12 8:54:59 点击:

  核心提示:1函数的参数类型函数可以作为参数进行传递。function showMsg(name,age,gender,showTime){// showTime = laoxieSay;// showTime ...

1函数的参数类型

函数可以作为参数进行传递。

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

// showTime = laoxieSay;

// showTime = function(){}

// showTime = '我看起来很年轻'

document.write('

我叫' + name + ', 今年' + age + '岁,' + gender + '

');

 

// 确定传进来的参数为function才执行

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

showTime();

}

}

function laoxieSay(){

document.write('其实我还小');

}

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

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

document.write('其实我不止28');

});

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假设当前函数已经可以使用,调用自身计算上一次的运行结果,再写出这次的运行结果。

Tags:10 06 6A AV 
作者:网络 来源:Hyperyou的博