四个使用this的典型应用

时间:2023-03-09 14:25:36
四个使用this的典型应用

(1)在html元素事件属性中使用,如

<input type=”button” onclick=”showInfo(this);” value=”点击一下”/>

(2)构造函数

function Animal(name, color) {

This.name = name;

this.color = color;

}

(3)<input type=”button” id=”text” value=”点击一下”/>

Var btn = document.getElementById(“text”);

Btn.onclick = function() {

Alert(this.value); //此处的this是按钮元素

}

(4)CSS expression表达式中使用this关键字

<table width="100" height="100">
<tr>
<td>
<div style="width: expression(this.parentElement.width);
height: expression(this.parentElement.height);">
division element</div>
</td>
</tr>
</table>
这里的this指代div元素对象实例本身。