js学习二函数

一、定义函数的两种方法:
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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值