javascript - 我该如何解决这个问题?我正在尝试在构造函数中获取方法,该方法将对两个数字执行代数
问题描述
我正在尝试在构造函数中获取方法,该方法将对两个数字执行代数,但没有任何效果
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
在另一个内部调用 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/
推荐阅读
- bash - 初始化标准输入以使 Bash 脚本可以接受多个标准输入?
- django - OAuth 回调 URL 与 nginx 代理服务器行为不兼容
- typescript - 添加@types/react-select 后输入错误
- c# - 使用 TryValidateModel 的问题
- javascript - 如何在点击按钮时产生这种悬停效果?
- javascript - 设置用户代理并发布
- javascript - 如何使用我自己的自定义下拉菜单控制 DataTables 生成的选择菜单?
- android - 为什么 jcenter()、maven()、google() 的位置在 build.gradle 中很重要
- android - 将 WordPress 网站转换为 PWA
- python - 避免多重嵌套 for 循环