• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
子涧
博客园    首页    新随笔    联系   管理    订阅  订阅
About “this” of Javascript

the 4 point about This:
1.the use of Object methods
2.the use of constructors
3.the use of ordinary function
4.the use of Function.prototype.call or Function.prototype.apply

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>this of point</title>
    <script>
        /*the use of Object methods*/
        var func={
            a:2,
            getA:function(){
              alert(this.a);
            }
        };
        func.getA();


        /*the use of ordinary function*/
        window.name='globle';
        var getNaem=function(){
            return this.name;
        };
        alert(getName());



        /*the use of constructors*/
        var myClass=function(){
            this.name='seven';
        };
        var obj=new myClass();
        alert(obj.name);
         /*warning:
          var myClass=function(){
            this.name='seven';
            return{
                name:'jack';
            }
          };
          var obj=new myClass();
          alert(obj.name);//jack

            如果构造器内部显式的返回了一个对象,那么次运算最终返回这个对象;
          */

        /*the use of Function.prototype.call or Function.prototype.apply*/
         var obj1={
             name:'seven',
             getName:function(){
                 return this.name;
             }
         };
        var obj2={
            name:'jezz'
        };
        alert(obj1.getName());
        alert(obj1.getName.call(obj2));






    </script>
</head>
<body>
<div id="div1"></div>

</body>
<script>
    /*expanding*/
    window.id='window';
    document.getElementById('div1').onclick=function() {
        alert(this.id);//div1
        var callback = function () {
            alert(this.id);//window
        };
        callback();
    };
    
   /* how to handle about this of point is changed*/
    /*Approach 1: keeps this for variables*/
    window.id='window';
    document.getElementById('div1').onclick=function() {
        var that=this;
        var callback = function () {
            alert(that.id);//div1
        };
        callback();
    };
    /* Approach 2:ues 'call' change*/*/
    window.id='window';
    document.getElementById('div1').onclick=function() {

        var callback = function () {
            alert(this.id);//div1
        };
        callback.call(this);
    };
</script>
</html>

  

posted on 2015-11-02 12:08  子涧  阅读(193)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3