鏈式調用
- 在每個函數內部return this
訪問對象屬性
- 點語法
[]
中括號內是字符串或是變量
數組是特殊的對象
對象屬性遍歷
- for in(遍歷對象或數組) - 不必再用Object.keys那么麻煩了
for(var key in obj){console.log(obj[key])// obj.key返回undefined// 因為js引擎會轉換為obj['key']
}
- instanceof
console.log([] instanceof Array) // true
console.log([] instanceof Object) // true
console.log({} instanceof Object) // true
- 類型判斷
var a = [] || {}
console.log(a.constructor)
console.log(a instanceof Array)
console.log(Object.prototype.toString.call(a))
// 實際運用時先緩存 var strFn = Object.prototype.toString// Object.prototype = {
// toString:function(){
// this.toString() // this → a
// }
// }
函數內部的this
- 只要沒有實例化構造函數,函數內部的this指向window
- 全局范圍的this指向window
- 構造函數內this指向
arguments.callee - 正在被執行的函數對象
function test(a, b, c, d) {console.log(arguments.callee.length)
}
test() // 4
- 應用,在自啟動函數中使用遞歸,且不需要函數名
var res = (function (n) {if (n <= 1) {return 1}return n = n + arguments.callee(n - 1)
})(10);
console.log(res) // 55
caller - 當前函數的調用者
- 嚴格模式下,使用arguments、callee、caller會報錯
dad()
function dad() {child()
}
function child() {console.log('child的調用者', child.caller)
}
練習
- typeof的返回值有幾種:6種
- 如何不用isNaN判斷NaN(轉換成字符串)
- 引用值對比的是地址(這個是比較,不是隱式類型轉換)
- 函數test的AO有a
apply、call傳null,this指向是什么
function Test(name) {this.name = name
}
function Test2() {Test.call(null, '測試')
}
console.log('obj', new Test2())