function fn() {
}
var a = 20;
function bar() {
var b = 10;
return a + b;
}
return bar();
fnO; 11 30
function 声明的函数比 var 明的变量有更加优先的执行顺序,即
我们常常提到的函数声明提前
函数表达式其实是将 个函数体赋值给一个变量的过程
var fn = undefined;
fn = function() {}
其中, var fn = undefined 会因为变量对象的原因而提前执行,这就是常常被提到的变
量提升 因此当我们使用函数表达式时,必须要考虑代码的先后顺序,这是与函数声明不同的地方
function Person(name
}
this.name =name;
this.age = age;
//在构造函 数内部添加方法
this . getAge = function() {
return this.age;
}
this .
// 给原型添加方法
Person.prototype.getName = function() {
return this.name;
}
// 在对象中添加方法
var a = {
m: 20,
getM: function() {
return this.m;
}
}
匿名函数就是没有名字的函数,一般会作为一个参数或者作为 个返回值来使
用,通常不使用变量来保存它 引用的常见的场景如下
数组中
var arr= (1, 2 , 3];
arr.map(function(item) {
return item + 1;
} )
arr.forEach(function(item){
//do something
})
函数作为返回值
unction add() {
var a = 10;
return function() {
return a + 20
}
}
add()();
(function() {
//
)();