JavaScript对象的3中this指向

1、构造函数中的方法、自定义函数中、new出的对象里添加方法去使用里边的值对于this指向的对象要清晰

实例

<script>
    //在对象中的方法里定义其它对象
    function Rect(width,height){
        this.width = width;
        this.height = height;
        this.cal = new Caculator();
        this.getArea = function(){
            //console.log("面积为:"+ this.cal.mul(this.width,this.height))
            var that = this;
            function print(){//自定义函数的话,则this指针指向的就是window
                console.log("面积为:"+ that.cal.mul(that.width,that.height))
            }
            print();
        }
    
        this.getCurc = function(){
            //console.log(this);
            var that = this;
           // console.log("上面的内容是getCurc中的this,下面的是this.cal.getC中的this")
            this.cal.getC = function(){
              
                //return (this.width + this.height) * 2//这里肯定不行,因为this指针指向的调用他的对象
                return (that.width + that.height) * 2
            }
            console.log("周长为:" + this.cal.getC());
        }
    }
    function Caculator(){
        this.mul = function(op1,op2){
            return op1 * op2;
        }
    }

    var rect1 = new Rect(8,20);
    var rect2 = new Rect(6,7);
    rect1.getL = function(){
        var that = this;
        this.cal.getL = function(){
            return that.width>that.height?that.width:that.height 
        };
        console.log("最长的边长为:"+this.cal.getL())
    }
    rect1.getArea();
    rect2.getArea();
    rect1.getCurc();
    rect1.getL();
   
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值