Javascript学习笔记-Function
一.Function Declaration
1)必须具有名字
2)在代码中,函数声明要么定义在全局范围内要么定义在函数体内
3)当进入调用上下文阶段就会创建函数声明
4)只是在调用上下文内对VO对象赋值有影响
5)定义的方式如下:
function functionDeclarationName(){
}
二.Function Expression
1)名字可选。
2)在代码中,定义在表达式位置
3)函数表达式对于在上下文内的VO对象没有影响
4)在代码执行阶段被创建
5)优势:避免污染全局的 VO对象
三.Immediately-Invoked Function Expression
1)在非表达式位置时候,如果需要创建立即执行的函数,则需要()圆括号操作符号。 例如:
(function () {})(); (function () {}());
2)在表达式位置时,如果需要创建立即执行的函数,则()圆括号可以省略。例如:
var foo = { bar: function (x) { return x % 2 != 0 ? 'yes' : 'no'; }(1) }; alert(foo.bar); // 'yes
3)在代码执行阶段创建函数,接着被立即自行,之后再被删除(如果没有被赋值给其他对象)
四。Function Statement(FS)
是Function的一个扩展实现,对于每个浏览器有自己不同的实现方式。 将其看成函数声明,在函数进入上下文阶段的时候创建并且可以保存成VO.
if (true) { function foo() { alert(0); } } else { function foo() { alert(1); } } foo(); // 1 or 0 ? test in different implementations
五。Named Function Expression (NFE)
FE with a name can call it self in the recursive way.
FE cann’t influence VO of context which means that it is impossilbe to call the function by the name befor or after the definiton)
(function foo(bar) { if (bar) { return; } foo(true); // "foo" name is available })(); // but from the outside, correctly, is not foo(); // "foo" is not defined
六.Functions created via Function constructor
1) [[Scope]]属性只能是Global
2)the functions created via Function constructor always require more memory resources,优化器不能作用与合并对象
var x = 10; function foo() { var x = 20; var y = 30; var bar = new Function('alert(x); alert(y);'); bar(); // 10, "y" is not defined }
七。函数构造过程
F = new NativeObject(); // property [[Class]] is "Function" F.[[Class]] = "Function" // a prototype of a function object F.[[Prototype]] = Function.prototype // reference to function itself // [[Call]] is activated by call expression F() // and creates a new execution context F.[[Call]] = <reference to function> // built in general constructor of objects // [[Construct]] is activated via "new" keyword // and it is the one who allocates memory for new // objects; then it calls F.[[Call]] // to initialize created objects passing as // "this" value newly created object F.[[Construct]] = internalConstructor // scope chain of the current context // i.e. context which creates function F F.[[Scope]] = activeContext.Scope // if this functions is created // via new Function(...), then F.[[Scope]] = globalContext.Scope // number of formal parameters F.length = countParameters // a prototype of created by F objects __objectPrototype = new Object(); __objectPrototype.constructor = F // {DontEnum}, is not enumerable in loops F.prototype = __objectPrototype return F