在 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
没有and的相同功能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));