【发布时间】:2016-11-15 13:54:18
【问题描述】:
制作一个接受新方法的计算器。但是当我添加一个新方法时,它看不到对象的“this”。为什么 Console.log 返回“未定义”?
function Calculator() {
this.numbers = function() {
this.numberOne = 2;
this.numberTwo = 5;
},
this.addMethod = function(op, func) {
this[op] = func(this.numberOne, this.numberTwo);
// WHY LOG RETURNS "undefined"?
console.log(this.numberOne);
}
}
let calc = new Calculator();
calc.addMethod("/", (a, b) => (a / b));
document.write(calc["/"]);
【问题讨论】:
-
第 5 行有错字:逗号应该是分号。
-
this.one从未设置,所以是的,它是undefined。 -
+goliadkin 我认为无论哪种方式都可以...
标签: javascript oop object methods this