码迷,mamicode.com
首页 > 编程语言 > 详细

About “this” of Javascript

时间:2015-11-02 13:44:21      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:

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>

  

About “this” of Javascript

标签:

原文地址:http://www.cnblogs.com/Expando/p/4929796.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!