【问题标题】:working with JS Classical with instance methods通过实例方法使用 JS Classical
【发布时间】:2015-07-12 15:33:28
【问题描述】:

我正在尝试分析经典模型的流程并测试不同的方法是否可行。首先,我已经实例化了ans1,然后我尝试将函数ans1.area 分配给ans2,相信它会通过引用但是当我尝试在ans2 中调用area() 时它不起作用 - ans2.area(),不应该是传递函数的引用吗?然而 当我将ans1 分配给ans2 并尝试调用ans2.area() 时,它与ans1 具有相同的值。你能帮忙并详细说明一下吗?谢谢。

  function Rectangle(length,width){

     this.length = length;
     this.width = width;

    }

    Rectangle.prototype.perimeter= function(){

       var perimeterAns = this.length + this.length + this.width + this.width;
       return perimeterAns;

      };

    Rectangle.prototype.area= function(){

          var areaAns = (2*this.length + 2*this.width);
          return areaAns;

      };


    var ans1 = new Rectangle(5,6);
    ans1.area(); // 22

    // not working
    var ans2 = ans1.area
    ans2(); // Nan

    ans2 = ans1;
    ans2.area(); // 22;

【问题讨论】:

  • var ans2 = ans1.area 缺少括号。应该是 ans1.area()
  • var ans2 = ans1.area 怎么样?为什么当我这样做时 - var ans2 = ans1.area ans2(); // Nan - 它返回 NaN。你能解释一下吗
  • 也不是更多this.length*this.width
  • 下面的答案很好...仅供参考,您还可以使用call()apply() 明确指定this 变量,例如var areaMethod = ans1.area; areaMethod.call(ans1);
  • 哈哈无视公式。

标签: javascript object prototype


【解决方案1】:

那是因为ans2 变量仅引用了area 函数,但缺少其原始上下文(这是ans1 变量引用的对象)。所以函数中的this 实际上是window(全局上下文),由于值无效,你最终会得到NaN

您可以使用bind 将函数绑定到原始上下文:

var ans2 = ans1.area.bind(ans1);

或者

var ans2 = Rectangle.prototype.area.bind(ans1);

MDN

【讨论】:

    【解决方案2】:

    当您执行 var ans2 = ans1.area; 时,您已经为 ans2 分配了一个函数。所以当你调用 ans2.area() 时,this 不是指一个 Rect 对象,它指的是全局对象,它没有t 具有 lengthwidth 属性。

    请参阅Custom Objects,了解其在 JavaScript 中的工作原理的简要说明

    【讨论】:

      【解决方案3】:

      正如您在function area 中看到的,请访问lengthwidth 变量的方式(使用this) - 这意味着从您想要操作的对象访问length and width 变量被执行。

      现在你的第一个问题,看我的答案内联 // not working var ans2 = ans1.area // Copy the function area to a variable ans2(); // Nan // here when you call the function, this object points to //global object where length and width is undefined

      第二个问题,内联找到我的答案 ans2 = ans1; ans2.area(); // 22;object assigns by reference, so when you call the function on second copy object then it like calling on the same object, thats why the same answer

      `

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多