1、函数也是对象
函数的创建==>底层都是new关键字创建函数
- 函数声明:
function sum(a,b){
console.log(a+b);
}
- 函数表达式:
1 var sum = function sum(a,b) {
2 console.log(a + b);
3 }
- new关键字创建函数
1 // 语法:var 变量名 = new Function ('形参1','形参2',...,'函数体中的代码')
2 var sum = new Function('a','b','console.log(a + b)');
3 sum(10,20);
2、函数内部this的指向
this的指向关键是看函数的调用方法
2.1 普通函数中this的指向
- this指向window
- 代码:
1 // 【在普通函数中this指向window】
2 // function fn() {
3 // console.log(this);
4 // }
5 // fn();
6
7 // var fn = function() {
8 // console.log(this);
9 // };
10 // fn();
11
12 // (function(){
13 // console.log(this);
14 // })();
15
16
17 // function fn1() {
18 // function fn2() {
19 // console.log(this);
20 // }
21 // fn2();
22 // }
23 // fn1();
2.2 构造函数中this的指向
- this指向当前创建的对象----在内存中开辟的空间
- 代码:
1 // 【在构造函数中this指向当前创建的对象】
2 function Student(name,age) {
3 this.name = name;
4 this.age =age;
5 }
6 // 原型中添加方法
7 Student.prototype.sayHi = function() {
8 console.log('我叫' + this.name);
9 };
10
11 var stu1 = new Student('张三',10); // ==>this指向stu1
12 var stu2 = new Student('李四',10); // ==>this指向stu2
2.3 对象方法中的this指向
- this指向调用者
- 代码:
1 // 【在方法中,this指向调用者。 对象.方法()】
2 function Student(name,age) {
3 this.name = name;
4 this.age =age;
5 }
6 // 原型中添加方法
7 Student.prototype.sayHi = function() {
8 console.log('我叫' + this.name);
9 };
10
11 var stu1 = new Student('张三',10); // ==>this指向stu1
12 stu1.sayHi(); // ==>方法sayHi中的this指向stu1
2.4 定时器中this的指向
- this指向window
- 代码:
1 // 【在定时器中this指向windnow】
2 setTimeout(function(){
3 console.log(this);
4 },5000);
2.5 事件处理程序中this指向
- this指向事件源
- 代码:
1 // 【在事件处理程序中,this指向事件源】
2 document.onclick = function() {
3 console.log(this);
4 };