「这是我参与2022首次更文挑战的第8天,活动详情查看:2022首次更文挑战」。
创建函数的三种方式:
- 函数声明 function
- 函数表达式
- 构造函数
函数声明 function
// 可以先调用再声明 原因:预解析 so可以先调用
foo()
function foo() {
console.log(1);
}
函数表达式
// 函数表达式 : 不可以先调用再声明
// var foo2
console.log(foo2); //undefined
// foo2()//foo2 is not a function
var foo2 = function () {
console.log(1);
}
构造函数
// 可以直接在 JavaScript 控制台中运行
// 创建了一个能返回两个参数和的函数
const adder = new Function("a", "b", "return a + b");
// 调用函数
console.log( adder(2, 6));;
// > 8
如果只有一个参数 那么参数作为新创建函数的函数体
var f = new Function("n1")
var f2 = new Function("console.log('hello')")
console.log(f);
console.log(f2);
Function 构造器与函数声明之间的不同
eval 很强大 但避免使用
eval(new String("2 + 2")); // 返回了包含"2 + 2"的字符串对象
eval("2 + 2"); // returns 4
函数的四种调用方式:
函数的四种调用方式
1.函数调用模式:
2.方法调用模式:
ps:. / 【】 指向前面的调用者
3.构造函数模式:
4.上下文模式:
this指向面试题:
注意:千万不要修改代码:
易错点:
1.任何一个函数都有属于自己的this指向
2.this的指向只看函数的调用模式 ,不看函数在哪里调用得到
2.
3. 10 2
- 10 3
函数也是对象,函数的原型链
通过dir拿:
找到Person 是通过 Function构造函数new 出来的
那么可以推断出父亲叫什么了
console.dir(Function.prototype === Person.__proto__);//true
js:
<script>
// function Person();
var Person = new Function()
//找妈妈 可以通过先找父亲
// console.log(Person.__proto__);
console.dir(Person.__proto__);
//父亲
console.dir(Function.prototype === Person.__proto__);//true
</script>