2016-09-28 59 views
3

我正在尋找擴大引導插件的正確方法,並發現了這樣的回答:https://stackoverflow.com/a/12689534/1276032什麼可能是使用jQuery.extend重寫函數的原因?

什麼困擾我,是最後一節 - 初始化覆蓋。下面複製的代碼:

// override the old initialization with the new constructor 
$.fn.modal = $.extend(function(option) { 

    var args = $.makeArray(arguments), 
     option = args.shift(); 

    return this.each(function() { 

     var $this = $(this); 
     var data = $this.data('modal'), 
      options = $.extend({}, _super.defaults, $this.data(), typeof option == 'object' && option); 

     if (!data) { 
      $this.data('modal', (data = new Modal(this, options))); 
     } 
     if (typeof option == 'string') { 
      data[option].apply(data, args); 
     } 
     else if (options.show) { 
      data.show.apply(data, args); 
     } 
    }); 

}, $.fn.modal); 

我不明白爲什麼$ .extend在這種情況下使用 - 它有一定的效果,我沒有看到?如果我執行此代碼:

var f1 = function(){console.log(1);}; 
var f2 = function(){console.log(2);}; 
var f2 = $.extend(f1,f2); 
f2(); 

然後只有1被打印到控制檯,並且f1等於f2。所以,看似簡單assingnment會做,

$.fn.modal = function(option) {...} 

但也許我錯過了什麼......

回答

0

您需要更改此:

$.fn.modal = $.extend(function(option) { 
    // your code ... 
}, $.fn.modal); 

此:

$.extend($.fn.modal, function(option) { 
    // your code ... 
}); 

TL; DR

$.extend(a, b)個拷貝b一個修改它的內容)的內容,並且如果任何重複的,那麼的b遺體的性質。此外,它返回值a

所以,如果你有這樣的:

hello = { unique_on_hello: 'hola', message: 'hello message' } 
world = { unique_on_world: 'mundo', message: 'WORLD MESSAGE' } 
response = $.extend(hello, world) 

每一個值將是:

hello // {unique_on_hello: "hola", message: "WORLD MESSAGE", unique_on_world: "mundo"} 
world // {unique_on_world: "mundo", message: "WORLD MESSAGE"} 
response // {unique_on_hello: "hola", message: "WORLD MESSAGE", unique_on_world: "mundo"} 

所以,如果你做f2 = $.extend(f1,f2);相同

$.extend(f1, f2) // Copy properties of f2 to f1 
f2 = f1 

來源:https://api.jquery.com/jquery.extend/

+1

Thx回覆。我知道如何爲對象擴展工作。我的問題的線索與一個案例有關,當函數作爲參數傳遞時。你的建議(改變'f2 = $ .extend(f1,f2)'爲'$ .extend(f2,f1)')並不能真正回答我的問題,因爲我不想改變任何東西 - 我只想學習,爲什麼這個代碼是一個公認的,並且實際上相當有爭議的答案的一部分(目前32個upvotes)。此外 - 改變這個代碼仍然沒有擴展任何東西。結果始終是第一個參數的函數。 –

相關問題