Javascript实战训练营

Javascript实战训练营

变量类型:

Null、Number、Boolean、String、Object、FunctionArrayRegExp

直接量:

执行速度:直接量>引用
对象直接量:
var a={name:'zeng',age:27};
函数直接量://表达式不是语句
var b=function(a,b){return a+b};    //运行 b();
function(a,b){return a+b;}()    //函数关键字语句
(function(a,b){return a+b;})()  //强制把function当块执行
特殊直接量:
var c=null;
var d=underfined;
var e='string';
var f=21;

什么是匿名函数

定位函数的三种方式:
function a(x){alert(x)};    //函数语句(但没有执行,需调用才执行,同时生成一个a对象)
var fn=function(x){alert};  //函数字面量(将匿名函数赋值给变量)
var fn=theAdd(a,b){return a+b}  //可执行函数变量名fn(a,b)或函数theAdd(a,b);理解为函数即对象
var fn=new function('x',alert(x));  构造函数
函数字面量和function()构造函数的区别
函数字面量是一个函名函数,可以指定函数名,递交函数时可调自己,使用new Function()构造函数则不行,构造函数每次执行时都解析函数主体,并创建新的函数对象。所以当一外循环阈频繁执行的函数调用Function()构造函数效率非常低。相反,函数字面量却不是每次遇到都重新编译。
function fact(x){
    if(x<=1){
        return 1;
    }else{
        return x*fact(x-1);
    }
}
用Function()构造函数创建一个函数并不遵循典型的作用域名,它一直都当作顶级函数来执行:
var y = "global"; 
function constructFunction() { 
    var y = "local"; 
    return new Function("return y"); // 无法获取局部变量
};
alert(constructFunction()()); // 输出 "global" 函数直接量:

定义对象的四种方式:(函数的调用方式)

1、构造函数为对象
function Animal(name){
    this.name = name;
    this.introduceSelf = function(){
        console.log("I am a " + this.name+"!");
    };
}
var dog = new Animal("dog");
dog.introduceSelf();
2、原型方式
fucntion Animal(){}
Animal.prototype.name = "animal";
Animal.prototype.introduceSelf = function(){
    console.log("I am a " + this.name+"!");
};
//对象的实例如下:
var dog = new Animal();
dog.name = "dog";
dog.introductSelf();
3、构造方式
function Animal(name){
    this.name = name;
}
Animal.prototype.introduceSelf = function(){
    console.log("I am a " + this.name+"!");
};
4、动态原型方式。
function Animal(name){
     this.name = name;
     if (typeof Animal._initialized  == 'undefined'){
        Animal.prototype.introduceSelf = function (){
             console.log( "I am a " + this.name + " ! ");
        };
        Animal._initialized = true;
    }
}

JavaScript作用域:

全局作用域(lobal Scope):

1、在代码任何地方都可以访问到的对象拥有全局作用域
2、所有未定义直接赋值的变量自动声明为拥有全局作用域
3、window对象内置的属性都拥有全局作用域:window.name、window.location、window.top等等

局部作用域(Local Scope):

和全局作用域相发,只限于代码片段内可以访问
function doSomething(){
    var blogName="梦想天空";
    function innerSay(){
        alert(blogName);
    }
    innerSay();
}
alert(blogName); //脚本错误
innerSay(); //脚本错误

作用域链(Scope Chain)

执行函数量会创建一个称为“运行期上下文(execution context)”的内部对象,运行期上下文定义函数执行环境,都有自己作用域链,用于标识符解析,当运行期上下文被创建时,它的作用域链初始化为当前运行函数所包含的对象。
#这些值按照它们出现在函数中的顺序被复制到运行期上下文的作用域链中。它们共同组成了一个新的对象,叫“活动对象(activation object)”,该对象包含了函数的所有局部变量、命名参数、参数集合以及this,然后此对象会被推入作用域链的前端,当运行期上下文被销毁,活动对象也随之销毁。
原文地址:https://www.cnblogs.com/eclipsecn/p/3356726.html