Java Enthusiast

3 Billion Devices Run Java

ES6 Classの小ネタ

当たり前っちゃ当たり前なんだけど、以下のような状況でselfもといthisがundefinedだと怒られる。実体はprototypeと何も変わらない。

class Foo {
	constructor() {
		this._foo = "Hello";
	}
	funcA() {
		let self = this;
		console.log(self._foo);
	}
}

function gFunc(func) {
	func();
}

var foo = new Foo();
gFunc(foo.funcA);

インスタンスから呼んでるんだからbindしといてくれてもいいのにと思ったんだが、そうはいかないみたい。次のように明示的にbindするとうまくいく。

class Foo {
	constructor() {
		this._foo = "Hello";
	}
	get funcA() {
		return this._funcA.bind(this);
	}
	_funcA() {
		let self = this;
		console.log(self._foo);
	}
}

function gFunc(func) {
	func();
}

var foo = new Foo();
gFunc(foo.funcA);