缘起:

{.line-numbers}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Counter{ 
private _i : number;
constructor(){
this._i = 0;
}
get(): number{
return this._i;
}
set(val: number): void{
this._i = val;
}
increment(): void{
this._i++;
}
}
var counter = new Counter();
console.log(counter.get());
counter.set(2);
console.log(counter.get());
counter.increment();
console.log(counter.get());

上面是一段typescript代码,编译成javascript如下:

{.line-numbers}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var Counter = /** @class */ (function () {
function Counter() {
this._i = 0;
}
Counter.prototype.get = function () {
return this._i;
};
Counter.prototype.set = function (val) {
this._i = val;
};
Counter.prototype.increment = function () {
this._i++;
};
return Counter;
}());
// Counter.prototype._i = 6;
Counter._i = 6;
var counter = new Counter();
console.log(counter.get());
counter.set(2);
console.log(counter.get());
counter.increment();
console.log(counter.get());

其中

1
2
//Counter.prototype._i = 6;
Counter._i = 6;

是我自己加上去的,然后发现Counter._i = 6;无法改变this._i的值。
于是我把Counter打印出来了,得到了[Function: Counter]
然后我在打印之前先赋值:Counter._i = 5;,得到了{ [Function: Counter] _i: 5 }
但是我把this打印出来,得到的是Counter {},与Couter.prototype一致。
Counter.prototype._i = 6;可以改变this._i的值。

总结:JS创建一个function的时候,同时会为其创建一个prototype对象(原型对象)。而在function中的this,就是指向这个prototype对象的。
this = [Function].prototype