js中的函数小结
一、函数的定义
1.函数声明 可以在函数声明前也可以在函数声明后调用
function add(i,j){
return i+j;
}
2.函数表达式 只可以在函数定义后调用
var add = function(i,j){
return i+j;
}
3.对象实例化 只可以在函数定义后调用,定义在全局作用域中,无法访问父函数的所有变量
var add = new Function("i","j","return(i+j)");
二、构造函数
构造函数的命名一般首字母大写
代码示例
function Car(type,color){
this.type = type;
this.color = color;
this.status = "stop";
this.light = "off";
}
var audi = new Car("audi","silver");
var benz = new Car("benz","black");
var ferrari = new Car("ferrari","yellow");
三、函数调用
1.构造函数调用
2.方法调用
3.1函数调用(this)
先看代码:
function add(i,j){
return i+j;
}
var myNumber = {
value:1,
double:function(){
var helper=function(){
this.value = add(this.value,this.value);//此句错误,this对象引用的是window
}
helper();
}
}
上述代码this引用不当,可以修改为下列代码:
function add(i,j){
return i+j;
}
var myNumber = {
value:1,
double:function(){
this.value=add(this.value,this.value);
}
}
3.2.函数调用(arguments)
arguments不是数组是Array-like对象,其有以下特性
arguments[index]访问参数
arguments.length获得参数数量
arguments.callee 此特性已经用的越来越少
代码展示:把arguments转换成数组
var args = Array.prototype.slice.apply(arguments);//借用Array.prototype.slice方法选中所有参数赋给args
4.apply(call)调用模式
代码提示:
function Point(x,y){
this.x=x;
this.y=y;
}
Point.prototype.move = function(x,y){
this.x +=x;
this.y+=y;
}
var p = new Point(0,0);
p.move(2,2);
var circle = {x:1,y:1,r:1};
var circle = {x:1,y:1,r:1};
p.move.apply(circle,[2,1]); //{x:3, y:2, r:1} circle作为this [2,1]作为参数
bind方法
function Point(x,y){
this.x=x;
this.y=y;
}
Point.prototype.move = function(x,y){
this.x +=x;
this.y+=y;
}
var p = new Point(0,0);
p.move(2,2);
var circle = {x:1,y:1,r:1};
var circle = {x:1,y:1,r:1};
var circlemove = p.move.bind(circle,[2,1]); //函数并没有立即执行
setTimeout(circlemove,1000); //延时后执行