JavaScript对象的3中this指向

    科技2024-07-14  71

    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>
    Processed: 0.014, SQL: 8