函数定义形式
函数定义方式
- 函数声明
function max(a, b) {
return a > b ? a : b;
}
- 函数表达式
var max = function (a, b) {
return a > b ? a : b;
};
- Function 构造函数实例化
var max = new Function("a", "b", "return a > b ? a : b;");
函数定义三要素
- 函数名:alert、parseInt
- 函数的参数:传递给函数名的值
- 函数的返回值:函数执行的返回结果
匿名函数
(function(){
console.log("立即执行");
})();
var min = function(a,b){
return a<b?a:b;
}
name属性
var f1 = function() {};
console.log(f1.name);
var f1 = new Function();
console.log(f1.name);
length属性
function fun1(){}
console.log(fun1.length);
function fun2(a,b){}
console.log(fun2.length);
arguments 对象
arguments
- 代表传入函数的实参
- 是函数中的局部变量 (内部变量)
- 只有调用函数时才可用
- 是一个类数组对象
- 打印实参个数
console.log(arguments.length);
console.dir(arguments);
类数组对象
- 与数组一样具有 length 和 index 属性
- 本质是 Object
双向绑定
function fun(a, b, c) {
console.log(a, b, c);
console.dir(arguments);
console.log(a === arguments[0]);
}
var obj = { x: 1, y: 2 };
fun(1, obj);
call/apply/bind方法
call() 方法
- 语法 :
bird.fly.call(me,7,8) - 作用:调用函数,并且改变函数执行的this指向
apply() 方法
- 语法:
bird.fly.apply(me,[11,12]); - 作用:调用函数,并且改变函数执行的this指向
bind() 方法
foo.bind(this)();
函数调用形式
function foo(){ }
var func = function(){ }
foo( );
func( );
(function () { } ) ( ) ;
function f ( ) {
this.method = function ( ) { };
}
var o = {
method : function ( ) { }
}
var p1 = new Person ( " Jack" );
p1.sayHi( );