2014-09-28 46 views
0

這段代碼應該做一個簡單的任務,即計算兩點之間的距離。其實我寫這段代碼來學習get和set的工作方式,因爲我是新的這個概念。但它不斷給我錯誤,如意想不到的逗號/分號在那裏,我找不到什麼實際問題。如果我想爲x和y變量設置新的值,我該如何實現這一點?我的意思是我可以將set屬性作爲函數處理,並將值簡單地發送給points.addition(5, 6,7,8)?添加獲取並設置爲構造函數的原型鏈

(function(){ 
    function Point(x1,x2,y1,y2){ 
     this.x1=x1; 
     this.x2=x2; 
     this.y1=y1; 
     this.y2=y2; 
    } 
    Point.prototype={ 
     get addition(){ 
      return Math.sqrt((this.x2-this.x1)+(this.y2-this.y1)); 
     }, 
     set addition(x1,x2,y1,y2){ 
      this.x1=x1; 
      this.x2=x2; 
      this.y1=y1; 
      this.y2=y2; 
     } 
    }; 
    var points=new Point(1,2,3,4); 
    console.log(points.addition); 
    })(); 

回答

1

這不是宣佈setter和getter的好方法。見the mozilla documentation

這裏活樣本與修復:

(function(){ 
 
    function Point(x1,x2,y1,y2){ 
 
     this.x1=x1; 
 
     this.x2=x2; 
 
     this.y1=y1; 
 
     this.y2=y2; 
 
    } 
 
    Object.defineProperty(Point.prototype, "addition", { 
 
     get: function() { 
 
      return Math.sqrt((this.x2-this.x1)+(this.y2-this.y1)); 
 
     }, 
 
     set: function (point) { 
 
      this.x1 = point.x1; 
 
      this.x2 = point.x2; 
 
      this.y1 = point.y1; 
 
      this.y2 = point.y2; 
 
     } 
 
    }); 
 
    var points = new Point(1,2,3,4); 
 
    console.log(points.addition); 
 
    document.getElementById("output").textContent = points.addition; 
 
})();
<div id="output"/>

+0

謝謝!你說這是不是一個好way..but這是不是錯了way.Then爲什麼我的代碼沒沒有工作? – 2014-09-28 18:55:10

+0

也許你使用Obsolete語法:'在過去,JavaScript支持定義getter和setters的幾種其他語法。其他引擎都不支持這些語法,並且在最近版本的JavaScript中已經刪除了支持。關於刪除內容以及如何適應這些刪除的更多細節,請參閱刪除語法的解析 – 2014-09-28 18:56:57

相關問題