我试图更加熟悉 Javascript OOP,所以我写了一个小测试脚本,但在测试时我总是遇到异常:
异常:
Uncaught TypeError: Cannot call method 'day' of undefined
代码:
(function () {
function Time (date) {
var self = this;
var timeInWeek = 604800000;
var timeInDay = 86400000;
var dateInMilliSeconds = date.getTime();
self.add = function (num) {
self.day = function () {
var newDate = new Date();
newDate.setTime(dateInMilliSeconds + (timeInDay * num));
return newDate;
};
};
};
var date = new Date();
var time = new Time(date).add(1).day();
console.log(time);
})();
当我在 IIFE 模式之外运行测试脚本时,我收到异常 Time is undefined
,我是 Javascript OOP 的新手,所以当我尝试阅读其他 Javascript 库时,一个很好的 block 已经结束我的头。感谢您的帮助。
最佳答案
add
方法返回 undefined 因为它没有 return
语句。该问题与 IIFE 的使用无关。
相反,add
方法只是在执行时添加(可能覆盖)day
方法,因此以下内容“有效”:
var time = new Time(date)
t.add(1); // returns undefined, but has a side-effect of adding "day" to t
t.day();
但是,我怀疑这个问题有两个方面:
add
应该返回
一个 Method Chaining 兼容类型的对象;这可以是同一对象(对于可变设计),也可以是新对象(对于不可变设计)。day
应直接添加到每个 Time 对象;这将使new Time(date).day()
起作用。
例如:
function Time (date) {
var self = this;
var timeInWeek = 604800000;
var timeInDay = 86400000;
var dateInMilliSeconds = date.getTime();
self.add = function (num) {
// The idea here is to return an object of the same type for "chaining".
// Here I returned a new Time object (you'll have to work out the details),
// although for mutable objects, "return self" would be appropriate.
return new Time(dateInMilliSeconds + (timeInDay * num));
};
self.day = function () {
// actually return the "day", whatever that is.
return ...;
};
};
虽然这是一个很好的练习,但对于生产代码,我建议 moment.js除非有其他令人信服的理由。 moment.js 的源代码(可能是一个很好的引用)在 github/moment 上. “添加”(带有遗漏和附加注释)看起来像:
add : function (input, val) {
// mutate this objects data (but not methods)
addOrSubtractDurationFromMoment(this, dur, 1);
// returns the same object for chaining
return this;
},
关于javascript - 在 Javascript OOP 中调用嵌套函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20383833/