在js环境中,this有很多指向(window、dom、object等),巧妙的利用this,可以有效的防止变量或方法被外界污染,保证代码健壮性,实例如下。

demo:

<!DOCTYPE html>
<html>
<head>
<title>Menu UI</title>
<meta charset="UTF-8" >
</head>
<body>

</body>
<script type="text/javascript">
function showMsg(msg){
  alert(msg);
}
var methods = {
  showMsg: function(msg){//定义了和外部同名的方法
    console.log(msg);
  },
  valid: function(){
    this.showMsg('提示信息');//通过this让showMsg的域直接指向methods,避免方法调用不对,这里就涉及到方法的查询机制了
  }
};
methods.valid();
</script>
</html>

console中运行结果:

this高级应用 - 域隔离

相关文章:

  • 2022-01-18
  • 2021-10-03
  • 2021-09-28
  • 2021-10-29
猜你喜欢
  • 2022-12-23
  • 2021-09-06
  • 2021-11-30
  • 2022-12-23
  • 2022-02-23
  • 2021-06-05
相关资源
相似解决方案