)1. js中的作用域是通过作用域链来实现的, 这个链, 是由一个一个的活动对象组成的, 最顶级的活动对象是window
2. 在js中, 在每一个执行点, this关键字都指当前函数(方法)的所有者.
3. 每个属性,其实都会定义成当前活动对象的属性, 在顶级文件中的每个函数定义,变量定义, 都定义成window对象的属性.
4. 对于函数, 如果通过函数表达式定义的函数, 则在函数表达式执行前, 该函数不可用. 而如果是通过函数定义式定义的函数, js会把它的定义提前, 也就是说在函数定义式之前, 该函数都可用.
5. 因为活动对象链的特性, 所以js支持闭包.
另外关于js中的原型链有一句要说的.
1. 只有函数对象有可以访问的prototype属性, 一般对象不是没有prototype属性, 只是没有可以访问的prototype属性.(严格来讲, 一般对象只有只能JS引擎内部访问的”[[prototype]]”属性)
之前 ECMAScript 3 的 specification 在這方面的用字真的使人在溝通上有點混亂,現在最新出的 ECMAScript 3.1 的 specification 實在好得多。以下用新用字說。
Javascript 是沒有宣告和定義之分的,宣告的同時就會定義,未宣告即是未定義,已宣告即是已定義,最起碼在語言中是檢查不出分別的。不過 var statement 的 declaration binding instantiation 和 assignment 卻是分開的。
例如:
var global = window;
alert(“declarativeVariable1″ in global); // display “true”
alert(declarativeVariable1); // display “undefined”
var declarativeVariable1 = “some value”; // variable declaration statement
alert(declarativeVariable1); // display “some value”
alert(declarativeFunction2); // display declarativeFunction2.toString()
function declarativeFunction2(){} // function declaration statement
alert(“functionExpression” in global); // display “false” for Javascript, “true” for Jscript which is wrong implementation of ECMAScript
try{
alert(functionExpression);
}catch(error){
alert(“error”);
} // display “error” for Javascript, functionExpression.toString() for Jscript which treat function expression as function declaration statment
alert(“declarativeVariable3″ in global); // display “true”
alert(declarativeVariable3); // display “undefined”
var declarativeVariable3 = function functionExpression(){};
alert(declarativeVariable3); // display functionExpression.toString()
alert(“functionExpression” in global); // display “false” for Javascript, “true” for Jscript
其實 Javascript 的 this 關鍵字有點複雜,既非靜態(詞法),亦非動態。先不理那些內部屬性、內部方法、call方法、apply方法。簡化了綜合地說,函式內的 this 的值是取決於函式呼叫時用以取出該函式的 Reference 的 base 值的,如果是一般的物件,則 this 就是指向該物件,如果是 declarative envirnoment record (即是一般的 scope),則 this 就是指向全域物件。
例如這樣:
var someString = “global variable”;
function enclosing(){
this.someString = “property 1″;
var someString = “local variable 1″;
function test(){alert(this.someString);}
test();
return test;
}
var someObject = {encolsing:encolsing};
var testGlobal = someObject.enclosing(); // display “global variable”
alert(someObject.someString); // display “property 1″
testGlobal(); // display “global variable”
secondObject = {someString:”property 2″,testProperty:testGlobal};
secondObject.testProperty(); // display “property 2″
with(secondObject)
var innerWith = function(){testProperty();};
innerWith(); // display “property 2″;
ECMAScript 3.1 (現在叫 ECMAScript 5th edition)的最新 specification 寫得很清晰,例如最新的 specification 把 scope 和一般物件清楚分開處理,並把 LexicalEnvironment 和 VariableEnvironment 分離,特別它把各操作和計算「函式化」和「物件導向化」。
good
var func = function(){} //函数表达式
function func(){} //函数定义式
function xx(){} //函数表达式?
xx = function(){}//函数定义式?
你那句话好拗口