js高级程序设计阅读第十章-函数

48 阅读1分钟

箭头函数没有 prototype 属性。

参数初始化顺序遵循“暂时性死区”规则,即前面定义的参数不能引用后面定义的。像这样就会抛 出错误: // 调用时不传第一个参数会报错

function makeKing(name = numerals, numerals = 'VIII') { 
return `King ${name} ${numerals}`; 
} 
参数也存在于自己的作用域中,它们不能引用函数体的作用域: 
// 调用时不传第二个参数会报错 
function makeKing(name = 'Henry', numerals = defaultNumeral) {
let defaultNumeral = 'VIII'; 
return `King ${name} ${numerals}`; 
}

arguments.calleefunction 和 caller

outer() {  
 inner(); 
} 
function inner() { 
 console.log(arguments.callee.caller); 
} 
outer();

箭头函数this指向上下文

function King() { 
 this.royaltyName = 'Henry'; 
 // this 引用 King 的实例
 setTimeout(() => console.log(this.royaltyName), 1000); 
} 
function Queen() { 
 this.royaltyName = 'Elizabeth'; 
 // this 引用 window 对象
 setTimeout(function() { console.log(this.royaltyName); }, 1000); 
} 
new King(); // Henry 
new Queen(); // undefined

new.target

function King() { 
 if (!new.target) { 
 throw 'King must be instantiated using "new"' 
 } 
 console.log('King instantiated using "new"'); 
} 
new King(); // King instantiated using "new" 
King(); // Error: King must be instantiated using "new"

函数的length是参数的个数

递归优化

const factorial = (function f(num) { 
 if (num <= 1) { 
 return 1; 
 } else { 
 return num * f(num - 1); 
 } 
}); 

尾调用优化 没看懂

[[Scope]]

箭头函数this看定义时的上下文 匿名函数this看执行时上下文

this执行

window.identity = 'The Window'; 
let object = { 
identity: 'My Object', 
getIdentity () { 
return this.identity; 
} 
}; 

object.getIdentity(); // 'My Object' 
(object.getIdentity)(); // 'My Object' 
(object.getIdentity = object.getIdentity)(); // 'The Window'
赋值时 object.getIdentity作为一个普通的函数 不是对象的方法 所以指向了window

立即调用的函数表达式

IIFE 内部定义的变量在外部访问不到。

// IIFE 
(function () { 
for (var i = 0; i < count; i++) { 
console.log(i); 
} 
})(); 
console.log(i); // 抛出错误