[英]When a method depends on another method
What is the best way to deal with the following situation in JavaScript. 用JavaScript处理以下情况的最佳方法是什么。
I have three methods ( m1
, m2
, m3
) and the last one ( m3
) depends from the results of the others two ( m1
, m2
). 我有三种方法(
m1
, m2
, m3
),最后一种方法( m3
)取决于其他两种方法( m1
, m2
)的结果。
In this way it works, but I am curious to know if there is a better way to write the code in this situation, especially for future developers that will read the code. 通过这种方式,它可以工作,但是我很想知道在这种情况下是否有更好的方式编写代码,特别是对于将来将要阅读代码的开发人员。
var O = function () {
this.p = 0;
}
O.prototype.makesomething = function () {
var that = this;
that.m1();
that.m2();
that.m3();
}
O.prototype.m1 = function () {O.p++}; // it changes the value O.p
O.prototype.m2 = function () {O.p++}; // it changes the value O.p
O.prototype.m3 = function () {return O.p}; // m3 depends by m1, m2 because it needs to get the update value of O.p
First, I don't know for sure, but putting this.p = 0
inside O
does not make sense in combination with Op
. 首先,我不确定,但是将
this.p = 0
放在O
中与Op
结合使用是没有意义的。 You probably mean this.p
inside m3
, when referring to the instance. 当引用实例时,您可能在
m3
内部表示this.p
Anyway, if you are looking for readability, you could make some simple but idiomatic functions like this: http://jsfiddle.net/ZvprZ/1/ . 无论如何,如果您正在寻找可读性,则可以制作一些简单但惯用的功能,例如: http : //jsfiddle.net/ZvprZ/1/ 。
var O = function () {
this.p = 0;
}
O.prototype.makesomething = function () {
var that = this;
var result = when( that.m1(), that.m2() )
.then( that.m3() );
return result;
}
O.prototype.m1 = function () {this.p++};
O.prototype.m2 = function () {this.p++};
O.prototype.m3 = function () {return this.p};
The when
/ then
can be rather straight-forward since it does not do anything than making it more readable: when
/ then
可能很简单,因为它除了使它更具可读性外没有做任何事情:
(function(window) {
var when, then, o;
when = function() {
return o; // just return the object so that you can chain with .then,
// the functions have been executed already before executing
// .when
};
then = function(a) {
return a; // return the result of the first function, which has been
// executed already (the result is passed)
};
o = { when: when,
then: then };
window.when = when; // expose
window.then = then;
})(window);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.