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



我试图在构造函数中获得方法,该方法将对两个数字执行代数,但没有任何工作

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);

你的代码不起作用的原因是在另一个function中调用function的方式是在同一个函数中声明它。例如:

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

只能在foo()内部调用bar()

如果你想调用一个在另一个函数内部的函数,你必须将它声明为一个属于那个函数的变量,就像下面的例子:

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());

由于methodconstructor内部,variablesconstructorscope中,因此在调用method时不需要传递它们。

下面是两个示例的工作小提琴:http://jsfiddle.net/xpjwqf72/2/

function algebra() {
a = prompt("enter");
this.a = parseInt(a);
b = prompt("enter");
this.b = parseInt(b);
this.sum = function() {
return (parseInt(a) + parseInt(b));
}
this.sub = function() {
return (a - b);
}
this.mul = function() {
return (a * b);
}
this.div = function() {
return (a / b);
}
return this;
}
var sum1 = new algebra();
console.log(sum1.sum());
console.log(sum1.sub());
console.log(sum1.mul());
console.log(sum1.div());

最新更新