JavaScript:陈述式申明 表达式申明 立即执行函数 与安全程式编码

204 阅读1分钟

立即执行函数的意义远不只是“立即执行”,它最大的作用是处理了变量范围,才能有了Node中模块化的概念,使得框架、库为我们所用。

function statement函数陈述式申明

function greet(name) {
    console.log('Hello ' + name);   
}
greet('John');

function expression函数表达式声明

var greetFunc = function(name) {
    console.log('Hello ' + name);
};
greetFunc('John');

Immediately Invoked Function Expression (IIFE)立即执行函数

var greeting = function(name) {
    
    return 'Hello ' + name;
    
}('John');

console.log(greeting);

var firstname = 'John';

(function(name) {
    
    var greeting = 'Inside IIFE: Hello';
    console.log(greeting + ' ' + name);
    
}(firstname)); 

var firstname = 'John';

(function(name) {
    
    var greeting = 'Inside IIFE: Hello';
    console.log(greeting + ' ' + name);
    
}(firstname));