一、定义函数的两种方法:
1.函数声明
function func(){
}
2.函数表达式
将匿名函数赋值给一个变量
var func = function(){
Uncaught ReferenceError: arguments is not defined
所以默认值应该是 undefined
js函数中有个储存参数的数组arguments ,所有函数获得的参数会被编译器挨个保存到这个数组中。
代码:
注意:
当参数是原始数据类型时,是值传递,原始数值不变;
当参数是对象数据类型时,是引用传递,会改变原有的对象;
三、作用域:
代码:
1.函数声明
function func(){
}
2.函数表达式
将匿名函数赋值给一个变量
var func = function(){
}
二、函数参数:
函数里的自带参数arguments,注意只在函数里才有,外部没有。arguments是一个数组,输出时报错:Uncaught ReferenceError: arguments is not defined
所以默认值应该是 undefined
js函数中有个储存参数的数组arguments ,所有函数获得的参数会被编译器挨个保存到这个数组中。
代码:
<pre name="code" class="html"><span style="font-size:14px;">var add = function(num1, num2) {
return num1+num2;
}
document.write('指定参数')
document.write(add(2))
// NaN
document.write(add(2,5))
// 7
document.write(add(2,5,6))
// 7
var addOpt = function () {
document.write(arguments[0])
var length = arguments.length,
sum = 0,
parameter;
for (var i=0;i<length;i++) {
parameter = arguments[i];
sum = sum + parameter;
}
return sum;
}
document.write('多参数')
document.write(addOpt(2))
// 2
document.write(addOpt(2,5))
// 7
document.write(addOpt(2,5,6))
// 13
document.write(addOpt(2,5,6,2))
// 15
document.write(arguments.length)</span>
注意:
当参数是原始数据类型时,是值传递,原始数值不变;
当参数是对象数据类型时,是引用传递,会改变原有的对象;
三、作用域:
限制了变量起作用的范围
四、作为对象属性
可以利用this指定当前对象
五、构造函数
提高了产生同类型对象的时间和代码量
代码:
<span style="font-size:14px;"><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Construction</title>
</head>
<body>
<script >
function Point(x, y) {
this.x = x;
this.y = y;
this.move = function(stepX, stepY) {
this.x += stepX;
this.y += stepY;
}
}
var point1 = new Point(1,1)
var point2 = new Point(2,2)
var point3 = new Point(3,3)
//point的值就是this,this是返回值
document.write('ponit');
document.write(point1);
// [object object]
document.write(point1.x)
point1.move(2,1) //(3,2)
point2.move(2,1) //(4,3)
point3.move(2,1) //(5,4)
</script>
</body>
</html></span>
六、原型代码:
<span style="font-size:14px;"><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ProtoType</title>
</head>
<body>
<script >
function Point(x, y) {
this.x = x;
this.y = y;
};
Point.prototype.move = function (stepX, stepY) {
this.x += stepX;
this.y += stepY;
};
// 公共属性或者方法
var point = new Point(1,1);
point.move(2,1);
console.log(point);
// document.write('point.x');
</script>
</body>
</html></span>
原型可以设置构造函数的实例共有的方法或者属性:Point.prototype.func(){}
注意prototype的写法不是protoType,否则会报错:
Uncaught TypeError: Cannot set property 'move' of undefined