2013-04-20 82 views
0

延長我的JavaScript對象,我有這樣的代碼:不能與原型

var Flippable = function(options, element) { 
    this.$el = $(element); 
    this._init(options); 
}; 

Flippable.prototype  = { 
    _init    : function(options) { 

     this.options  = $.extend(true, {}, $.Flips.defaults, options); 
     this.$pages   = this.$el.children('div.f-page'); 
     this.pagesCount  = this.$pages.length; 
     this.History  = window.History; 
     this.currentPage = this.options.current; 
     this._validateOpts(); 
     this._getWinSize(); 
     this._getState(); 
     this._layout(); 
     this._initTouchSwipe(); 
     this._loadEvents(); 
     this._goto(); 

    }, 
    foo: function(){alert("foo");} 
} 

但是當我打電話Flipppable.foo(),我得到了一個未定義。任何想法,我的語法關閉?

謝謝!

克里斯

** **更新

我的「M創建了以下這樣一個插件:

$.fn.flippable = function(method) { 

// Method calling logic 
if (Flippable[method]) { 
    return Flippable[ method ].apply(this, Array.prototype.slice.call(arguments, 1)); 
} else if (typeof method === 'object' || ! method) { 
    return Flippable._init.apply(this, arguments); 

遺漏的類型錯誤:無法調用未定義 '申請'}其他{ $ .error('Method'+ method +'在jQuery.flippable上不存在'); }

};

它borks在線:

return Flippable._init.apply(this, arguments); 

_init是不確定的。

+1

你用'new Flippable()'創建了一個對象嗎? PS:通常修改'prototype',而不是完全覆蓋。 – zerkms 2013-04-20 12:32:33

回答

2

原型函數只能通過類的對象訪問。而不是班級本身。 這將工作。

var oFlip = new Flippable(); 
oFlip.foo(); 
+0

它們也可以通過Flippable的原型對象訪問,因爲這是它們聲明的地方。 – 2013-04-20 12:45:48

0

您嘗試使用.apply調用foo的方式,您將不得不這樣做。

Flippable.prototype.foo.apply(this, arguments); 

具有foo屬性的對象是Flippable上的原型,而不是Flippable本身。