将get和set添加到构造函数的原型链中

add get and set to the prototype chain of a constructor

本文关键字:原型 构造函数 get set 添加      更新时间:2023-09-26

这段代码应该做一个简单的任务,即计算两点之间的距离。事实上,我写这段代码是为了学习get和set是如何工作的,因为我对这个概念还很陌生。但它总是给我错误,比如意外的逗号/分号。我不知道实际的问题是什么。

我还有一个问题,如果我想为x和y变量设置新的值,我该如何实现??我的意思是,我可以把set属性当作一个函数,并简单地发送值。加法(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);
   })();

这不是声明setter和getter的好方法。请参阅mozilla文档。

这里有一个带修复程序的活样本:

(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"/>