开发者社区 问答 正文

写出 3 个使用 this 的典型应用

写出 3 个使用 this 的典型应用

展开
收起
pandacats 2019-12-10 16:49:26 865 分享 版权
1 条回答
写回答
取消 提交回答
  • (1)、在 html 元素事件属性中使用,如: input type=”button” onclick=”showInfo (this);” value=” 点击一下” (2)、构造函数

    function Animal(name, color) {
      this.name = name;
      this.color = color;
    }
    

    (3)input 点击,获取值

    var btn = document.getElementById("text");
    btn.onclick = function() {
    alert(this.value); //此处的this是按钮元素
    }
    

    (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
    
    2019-12-10 16:49:41
    赞同 展开评论
问答地址: