Sunday, November 22, 2009

Javascript Argument

Here, transparent() is created as a function of the options object. The function accepts an argument, opacity. Calling the function without passing the argument will always return false because comparing null to a value gives false.
> var options = {backgroundColor:"#ffcccc", opacity:0.5};
> options.fontSize="2em";
> options.transparent = function (opacity) { return opacity < 1.0; }

> options
   backgroundColor: "#ffcccc"
   fontSize: "2em"
   opacity: 0.5
   transparent: function (opacity) { return opacity < 1.0; }

> options.transparent
   function (opacity) { return opacity < 1.0; }

> options.transparent();
   false

> options.transparent(0.5);
   true
Modify the function slightly to verify the theory of why false is returned when no argument is passed.
> options.transparent = function(opacity) { if (opacity == null) return null; return opacity < 1.0; }

> options.transparent()
   null

> options.transparent(0.1)
   true
As a review of the interaction between the DOM and Javascript, we dynamically add a link to a page.
> var a = document.createElement("a");
> a.href="http://google.com";
> a.innerText="Google";
> document.body.appendChild(a);
Extending jQuery, adding a function:
> jQuery.extend({ aFunc:function() {}, }); //$.aFunc()
Extending jQuery, adding a method:
> jQuery.fn.extend({ aFunc:function() {}, }); // $('. a').aFunc()