函数声明和函数调用

2017-09-11  本文已影响15人  YM雨蒙

函数声明定义函数特点

函数实例化定义函数特点

变量前置

console.log(a)   //undefined
var a = 3    

==>等同于

var a
console.log(a)
a = 3

函数声明

console.log(sum(3,5))

function sum(a,b){
  return a + b
}

==>等同于
  

function sum(a,b){
  return a + b
}

console.log(sum(3,5))

函数表达式声明前置

fn()  //"TypeError: fn is not a function(不是一个函数)

var fn = function(){
  console.log('fn...')
}

==>


var fn
fn()

fn = function(){
  console.log('fn...')
}

立即执行函数

立即执行函数可以形成一个作用域,和全局隔开,不会污染全局,另一方面也是防止命名冲突的影响

(function(){
  console.log('我是立即执行函数')
})()

==>
  
var fn = function(){
  console.log('我是立即执行函数')
}
fn()

命名冲突

当在同一个作用域内定义了名字相同的变量和方法的话,会根据前置顺序产生覆盖

var fn = 3;
function fn(){}

console.log(fn); // 3

==>

var fn
function fn(){}  //覆盖上面的

fn = 3  //重新赋值
console.log(fn)

console.log(fn); // 3

function fn(){}
var fn = 3;

==>
function fn(){}  
var fn  //已经声明的值不会变

console.log(fn)  //fn(){}
fn = 3  

递归

简单来说就是自己调用自己

function factorial(n){
  if(n === 1){
    return 1
  }
  return n * factorial(n-1) 
}
alert(factorial(3))

//缺点:效率低

函数调用

var myNumber = {
 value: 1,
 add: function(i){
  console.log(this);
  this.value += i;
  }
}
myNumber.add(1);

函数调用模式的区别-this

//例子:
function add(i,j){
  console.log(this);  //Window
  // console.log(arguments);
  var sum = i+j;
  console.log(sum);
  (function(){
    console.log(this);  //Window
  })()
  return sum;
}
add(1,2);
//例子:
var myNumber = {
  value: 1,
  add: function(i){
    console.log(this);  //Object{value: 1, add: ƒ}
    this.value += i;
  }
}
myNumber.add(1);
//例子:
function Car(type,color){
  this.type = type;
  this.color = color;
  this.status = "stop";
  this.light = "off";
  console.log(this);  //打印结果是我们创建的对象
}
Car.prototype.start = function(){
  this.status = "driving";
  this.light = "on";
  console.log(this.type + " is " + this.status);
}
Car.prototype.stop = function(){
  this.status = "stop";
  this.light = "off";
  console.log(this.type + " is " + this.status);
}
var benz = new Car("benz", "black");  //Car {type: "benz", color: "black", status: "stop", light: "off"}

函数传参

var count = 1;
var addOne = function(num) {
    num += 1;
    return num;
}
var ret = addOne(count);
console.log(ret);  //2
console.log(count);  //1结果没有受到影响
//例子一:
var count = {a:1,b:1};
var addOne = function(obj) {
    obj.a += 1;
    obj.b += 1;
    return obj;
}
var ret = addOne(count);
console.log(ret);  //{a: 2, b: 2}
console.log(count);  //{a: 2, b: 2}

//例子二:
var count = {a:1,b:1};
var addOne = function(obj) {
    obj = {a:2, b:2};
    return obj;
}
var ret = addOne(count);
console.log(ret);  //{a: 2, b: 2} 
console.log(count);  //{a: 1, b: 1}
函数传参
上一篇下一篇

猜你喜欢

热点阅读