场景
我有一个 JavaScript 对象。此对象包含一个函数,该函数将根据 boolean
属性执行 statementA
或 statementB
。 boolean
属性应该被认为是只读的,为了论证,我们假设它是在构造函数中设置的。
代码
var MyClass = function(flag) {
this.flag = flag; // this will never change after here
}
MyClass.prototype.go = function() {
if (this.flag) {
this.go = function() {
// statement a (true)
};
} else {
this.go = function() {
// statement b (false)
}
}
this.go();
}
问题
从自身范围内重新分配一个方法是不好的做法吗?我曾尝试对此进行一些研究,但到目前为止我一直没有成功。
最佳答案
它是一样的,但更具可读性:
var MyClass = function (flag) {
this.flag = flag; // this will never change after here
this.go = flag ? function () {
// statement a (true)
} : function () {
// statement b (false)
};
}
关于javascript - 从自身内部重新分配 JavaScript 函数是不好的做法吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31180809/