在類的構(gòu)建過程中,對于一個特定值的訪問既可以使用屬性也可以使用方法例子://實現(xiàn)//Point類,表示平面上的一個點function Point(x,y){ this.x = x; this.y = y; //距原點的距離,使用屬性來實現(xiàn) Object.defineProperty(this,"distance",{ get: function(){ return Math.sqrt(this.x*this.x + this.y*this.y); } });}//距原點的距離,使用方法來實現(xiàn)Point.prototype.getDistance = function(){ return Math.sqrt(this.x*this.x + this.y*this.y);}//訪問var a = new Point(3,5);//使用屬性訪問Console.log(a.distance);//使用方法訪問Console.log(a.getDistance());問題:在哪些情況下應(yīng)使用屬性,在哪些情況下應(yīng)使用方法?使用屬性和使用方法各有哪些優(yōu)缺點?有哪些介紹相關(guān)內(nèi)容的文章或書籍?
在類中,什么時候應(yīng)使用屬性,什么時候應(yīng)使用方法?
狐的傳說
2018-09-13 10:13:41