this调用指向
js中this并不确定指向,只有到调用时才真正确定。在js编程中一般不会用到this,只有在以下复杂的数据环境或面向对象才会使用。下面举个简单例子:
// test.js
console.log(this); // 非严格模式下为window 严格模式为undefined
// 定义函数 基类Animal
function Animal(name) {
// 这里的this并不确定
this.name = name;
this.say = function() {
console.log('I\'m ' + this.name || '');
// 返回this用于链式调用
return this;
}
}
// new Animal相当于将ani作为this指向Animal
let ani = new Animal('牛');
ani.say();
// 等价写法
// let ani = {}
// Animal.call(ani, '牛');
// ani.say();
// 定义函数 派生类Fish
function Fish(name, food) {
// copy基类Animal属性方法到this
Animal.call(this, name);
this.food = food;
this.eat = function() {
console.log('I eat ' + this.food || '');
}
}
let carp = new Fish('鲤鱼', '水草');
carp.say().eat();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
上次更新: 2025/09/05, 8:09:00