首页 > 解决方案 > 我该如何解决这个问题?我正在尝试在构造函数中获取方法,该方法将对两个数字执行代数

问题描述

我正在尝试在构造函数中获取方法,该方法将对两个数字执行代数,但没有任何效果

function algebra() {
  a = prompt("enter");
  this.a = parseInt(a);

  b = prompt("enter");
  this.b = parseInt(b);

  function sum(a, b) {
    return (a + b);
  }

  function sub(a, b) {
    return (a - b);
  }

  function mul(a, b) {
    return (a * b);
  }

  function div(a, b) {
    return (a / b);
  }
}

var sum1 = new algebra();

console.log(sum1.sum);

标签: javascriptmethodsconstructor

解决方案


您的代码不起作用的原因是因为function在另一个内部调用 a 的方法function是在同一个函数上声明它。例如:

function foo() {
  function bar() {
    return "foo bar";
  }
}

调用的唯一方法bar()是在内部调用foo()

如果要调用另一个函数内部的函数,则必须将其声明为属于该函数的变量,如下例所示:

function foo() {
  this.bar = function() {
    return "foo bar";
  }
}

使用这种方法,您可以:

let foobar = new foo();

foobar.bar();

获得相同结果的另一种方法是使用class.

class algebra {
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
  
  sum() {
    return (this.a + this.b);
  }
}

let sum1 = new algebra(4, 5);
sum1.sum(); // output 9

这是您的代码工作:

// or simply do function algebra() {...} instead of let algebra = function() {...} both work
let algebra = function() {
  a = prompt("enter");
  this.a = parseInt(a);

  b = prompt("enter");
  this.b = parseInt(b);

  this.sum = function() {
    return (this.a + this.b);
  }

  this.sub = function() {
    return (this.a - this.b);
  }

  this.mul = function() {
    return (this.a * this.b);
  }

  this.div = function() {
    return (this.a / this.b);
  }
}

var sum1 = new algebra();
console.log(sum1.sum());

由于method是在里面,constructor而在variables是在constructor scope,你不需要在调用a时传递它们method

这是两个例子的工作小提琴:http: //jsfiddle.net/xpjwqf72/2/


推荐阅读