浅谈js里的this
this是Javascript中的一个关键字,它代表函数运行时,自动生成的一个内部对象,指向调用函数的那个对象
两个例子
首先来看几个例子,改编自阮一峰老师的博客
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 35 36 37 38
| var name = "The Window"; var object1 = { name : "My Object1", getNameFunc : function(){ return this.name } }; var object2 = { name : "My Object2", getNameFunc : () => this.name }; var object3 = { name : "My Object3", getNameFunc : function(){ return function(){ return this.name; }; } }; var object4 = { name : "My Object4", getNameFunc : function(){ var that = this; return function(){ return that.name; }; } }; console.log(object1.getNameFunc()); console.log(object2.getNameFunc()); console.log(object3.getNameFunc()()); console.log(object4.getNameFunc()());
|
对比object1和object2,this在function函数中指向object1,在箭头函数中就指向object2的父对象,即全局对象global/window
如果嵌套函数的话,如object3,第二层的函数又会重新指向全局对象global/window
如object4,可以使用 that = this
的方法,获得this的指向
class constructor中的 this
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
| class Polygon { constructor(height, width) { this.name = 'Polygon'; this.height = height; this.width = width; this.func = () => console.log(this.name) } sayName() { console.log('Hi, I am a ', this.name + '.'); } } class Square extends Polygon { constructor(length) { this.height; super(length, length); this.name = 'Square'; } get area() { return this.height * this.width; } set area(value) { this.height = this.width = Math.sqrt(value); } }
|