html 要素で使用する場合this
、DOM 内の要素を参照します。
例:
<script type="text/javascript">
function hover(domElement) {
domElement.style.backgroundColor = '#CCC';
}
</script>
<div onmouseover="hover(this);">Hover me</div>
を返さない関数で使用するthis
と、関数はオブジェクト コンストラクターになりthis
、暗黙的に作成されたオブジェクトを参照します。このオブジェクトは、関数が で呼び出されたときに自動的に返されますnew
。
例:
function Point(x, y) {
this.x = x || 0;
this.y = y || 0;
this.distance = function (point) {
return Math.sqrt(
Math.pow(point.x - this.x, 2) +
Math.pow(point.y - this.y, 2)
);
};
}
var a = new Point(10, 10);
var b = new Point(100, 100);
document.write(a.distance(b));
this
となしの同じ関数new
:
function Point(x, y) {
obj = {};
obj.x = x || 0;
obj.y = y || 0;
obj.distance = function (point) {
return Math.sqrt(
Math.pow(point.x - this.x, 2) +
Math.pow(point.y - this.y, 2)
);
};
return obj;
}
var a = Point(10, 10);
var b = Point(100, 100);
document.write(a.distance(b));