[英]Calling nested functions in Javascript OOP
我試圖變得更加熟悉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
的異常,這是Java OOP的新手,因此,當我嘗試閱讀其他Javascript庫時,我感到頭大了。 任何幫助表示贊賞。
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
應該return
兼容類型的對象方法鏈接 ; 這可以是同一對象(用於可變設計),也可以是新對象(用於不可變設計)。
應將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;
},
您已經錯過了return this;
(必須存在以允許菊花鏈連接)
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;
};
return this; //this
};
};
如果沒有return
語句,則在new Time(date).add(1).day())
將day()
視為由new Time()
實例的add
方法返回的值的方法。 如果add
方法沒有返回具有day
方法的對象,那么您肯定會出錯。
該return this
僅對於鏈接是必需的。 您的代碼可以正常工作
var time = new Time(date);
time.add(1);
time.day();
要么
var time = new Time(date).add(1);
time.day()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.