简体   繁体   中英

optional arguments in the constructor of an object (or method) javascript

I am studying a jQuery plugin that is called jQuery TE. In the constructor method there is an argument 'options' that is passed :

$.fn.jqte = function(options)

Normally then when calling this method, we must pass it 'options' argument like this:

$(".editor").jqte({
    "css":"example",
    "source":false,
    "titletext":false
});

I do not understand that we are not obliged to pass it this argument 'options' like this:

$(".editor").jqte();

Indeed it does not cause any errors. I do not see anywhere in the source code control something that the argument 'options' is present.

Who can explain this to me, I can not find resources on this problem goes anywhere. Maybe I misread the source code?

Here is the link to the documentation : http://jqueryte.com/documentation

Thanks !

Looking into the source of this plugin, you can find that the options are passed to jquery.extend() , which will Merge the contents of two or more objects together into the first object ( Source ).

You can look at it like this:

var default = {left: 0, bottom: 3};
var options = {left: 1, top: 1}

var result = $.extend(default, options); // {left: 1, top: 1, bottom: 3};

jQuery extend, in it's turn, allows the second parameter to be passed to be false. If it is false, (or nonexistent, or undefined, or...) then it will just return the first argument ('defaults'). This means that all the options you could possible pass are in the defaults array anyway, meaning if you don't pass options, it will not change the defaults at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM