- arguments
這個對象主要用來存放函數(shù)的參數(shù),但是他還有一個特殊的屬性,callee拜英,他是一個指針,指向擁有這個arguments屬性的函數(shù)琅催。
這是一個很好的居凶,用于解耦的屬性,比如經(jīng)典階乘函數(shù):
function factorial(num){
return num <=1 ? 1 : num * factorial(num-1);
}
//當將這個函數(shù)指針賦值給另外的變量藤抡,清除原來的函數(shù)指針侠碧,就會表現(xiàn)出他的耦合性
var temp = factorial;factorial = null;
temp(); //出問題
//利用callee解耦
function factorial(num){
return num <=1 ? 1 : num * arguments.callee(num-1);
}
PS:在嚴格模式下是不能調用callee屬性(還有caller屬性,用于輸出誰調用了擁有該caller屬性的函數(shù))的:
Paste_Image.png
- this
this引用的是函數(shù)執(zhí)行的環(huán)境對象缠黍。換句話可以說弄兜,函數(shù)屬于哪個對象的,那么該函數(shù)this對象引用的就是這個對象(PS:在頁面的全局作用域中調用函數(shù)時,this對象引用的是window對象)替饿。
window.color = "red";
var obj = { color: "blue" };
function sayColor(){
console.log(this.color);
}
sayColor(); //輸出red
obj.sayColor = sayColor;
obj.sayColor(); //輸出blue
//這里說函數(shù)內的this對象引用的是window對象语泽,要和使用構造函數(shù)模式常見對象的函數(shù)區(qū)別:
function Person(name, age){
this.name - name;
this.age = age;
this.sayName = function(){
console.log(this);
}
}
var person1 = new Person('a', 18);
//如果你直接調用Person這個構造函數(shù),this對象引用的還是window對象视卢,但
//是用new操作符新建一個實例湿弦,就相當于構造了一個Person對象,因此這個
//時候的this對象引用的是Person對象
person1.sayName(); //打印的是Person對象
Paste_Image.png