2013-10-20 71 views
1

我有這樣的代碼:爲什麼`this`永遠是構造函數中的`Window`對象?

(function() { 

    function App(elements, options) { 

    if (!this instanceof App) return new App(elements, options); 

    var that = this; 

    return this; 

    } 

    window.App = App; 

})(); 

App(document.querySelectorAll('.Slider-slide'), { 
    interval: 5000 
}); 

我的問題是,它從不創建的App一個新的實例,因此,this進一步下跌的代碼始終是Window對象,任何想法,爲什麼?

+4

因爲你不與沒有新的呼叫 – megawac

+0

@megawac intializing應用必要:http://ejohn.org/blog/simple-class-instantiation/ – benhowdle89

+0

我提供了一個答案的例子,將使案件真正@ benhowdle89 – megawac

回答

0

更新在穆薩的回答說,該代碼可以用這兩種2種模式的修正:

(function() { 

    function App(elements, options) { 

    if (!(this instanceof App)) return new App(elements, options); 

    var that = this; 

    } 

    window.App = App; 

})(); 

var myapp = App(document.querySelectorAll('.Slider-slide'), { 
    interval: 5000 
}); 

class結構不需要new電話:

(function() { 
    function App(elements, options) { 
     var that = this; 
    } 

    //calling window.App(/*stuff*/) will always return a new class 
    window.App = function(elements, options) { 
     return new App(elements, options); 
    }; 
})(); 

一小記事 - 當你創建一個類時,你不需要返回它,因爲這是隱式處理的。

+0

您是否閱讀過我發佈的鏈接或者查看@ musa的回答!? – benhowdle89

+0

@ benhowdle89是的,我最初誤解了代碼,我更新了答案 – megawac

相關問題