【问题标题】:add get and set to the prototype chain of a constructor将 get 和 set 添加到构造函数的原型链
【发布时间】:2014-09-28 18:40:54
【问题描述】:

这段代码应该做一个简单的任务,即计算两点之间的距离。实际上,我编写这段代码是为了了解 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);
   })();

【问题讨论】:

    标签: javascript get set


    【解决方案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"/>

    【讨论】:

    • 谢谢!!你说这不是一个好方法..但这不是错误的方法。那为什么我的代码不起作用??
    • 也许你使用过时的语法:In the past, JavaScript supported several other syntaxes for defining getters and setters. None of these syntaxes were supported by other engines, and support has been removed in recent versions of JavaScript. See this dissection of the removed syntaxes for further details on what was removed and how to adapt to those removals.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-16
    • 2019-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多