this的典型應用場景
阿新 • • 發佈:2018-12-10
1)、在html元素事件屬性中使用,如:
<input type=”button” onclick=”showInfo(this);” value=”點選一下”/>
(2)、建構函式
function Animal(name, color) { this.name = name; this.color = color; }
(3)、input點選,獲取值
<input type="button" id="text" value="點選一下" /> <script type="text/javascript"> var btn = document.getElementById("text"); btn.onclick = function() { alert(this.value); //此處的this是按鈕元素 } </script>
(4)、apply()/call()求陣列最值
var numbers = [5, 458 , 120 , -215 ]; var maxInNumbers = Math.max.apply(this, numbers); console.log(maxInNumbers); // 458 var maxInNumbers = Math.max.call(this,5, 458 , 120 , -215); console.log(maxInNumbers); // 458