Skip to main content

Home/ javascript/ Group items tagged function

Rss Feed Group items tagged

Javier Neira

Perfection kills » Understanding delete - 3 views

  • All because it’s not possible to delete variables in Javascript. At least not when declared in such way.
  • It’s almost as if Firebug follows some other rules of deletion. It is Firebug that has led Stoyan astray! So what is really going on here?
  • we need to understand how delete operator works in Javascript: what exactly can and cannot be deleted and why.
  • ...35 more annotations...
  • var o = { x: 1 }; delete o.x; // true o.x; // undefined
  • var x = 1; delete x; // false x; // 1
  • function x(){} delete x; // false typeof x; // "function"
  • Note that delete only returns false when a property can not be deleted.
  • variable instantiation and property attributes
  • Global code, Function code and Eval code.
  • When a source text is treated as a Program, it is executed in a global scope, and is considered a Global code.
  • Anything that’s executed directly within a function is, quite obviously, considered a Function code. In browsers, content of event attributes (e.g. <p onclick="...">) is usually parsed and treated as a Function code.
  • text that’s supplied to a built-in eval function is parsed as Eval code. We will soon see why this type is special.
  • And now that we know the difference between property assignment and variable declaration — latter one sets DontDelete, whereas former one doesn’t — it should be clear why undeclared assignment creates a deletable property:
  • As you can see, execution contexts can logically form a stack. First there might be Global code with its own execution context; that code might call a function, with its own execution context; that function could call another function, and so on and so forth. Even if function is calling itself recursively, a new execition context is being entered with every invocation.
  • Every execution context has a so-called Variable Object associated with it. Similarly to execution context, Variable object is an abstract entity, a mechanism to describe variable instantiation. Now, the interesing part is that variables and functions declared in a source text are actually added as properties of this Variable object.
  • When control enters execution context for Global code, a Global object is used as a Variable object. This is precisely why variables or functions declared globally become properties of a Global object:
  • The behavior is actually very similar: they become properties of Variable object. The only difference is that when in Function code, a Variable object is not a Global object, but a so-called Activation object. Activation object is created every time execution context for Function code is entered.
  • and a special Arguments object (under arguments name). Note that Activation object is an internal mechanism and is never really accessible by program code.
  • within Eval code are created as properties of calling context’s Variable object. Eval code simply uses Variable object of the execution context that it’s being called within:
  • Execution context When ECMAScript code executes, it always happens within certain execution context.
  • When declared variables and functions become properties of a Variable object — either Activation object (for Function code), or Global object (for Global code), these properties are created with DontDelete attribute. However, any explicit (or implicit) property assignment creates property without DontDelete attribute. And this is essentialy why we can delete some properties, but not others:
  • Special arguments variable (or, as we know now, a property of Activation object) has DontDelete. length property of any function instance has DontDelete as well:
  • As you might remember, undeclared assignment creates a property on a global object.
  • Now that it’s clear what happens with variables (they become properties), the only remaining concept to understand is property attributes. Every property can have zero or more attributes from the following set — ReadOnly, DontEnum, DontDelete and Internal. These attributes serve as sort of flags — an attribute can either exist on a property or not. For the purposes of today’s discussion, we are only interested in DontDelete.
  • Variables declared within Eval code are actually created as properties without DontDelete:
  • This interesting eval behavior, coupled with another aspect of ECMAScript can technically allow us to delete non-deletable properties. The thing about function declarations is that they can overwrite same-named variables in the same execution context:
  • Note how function declaration takes precedence and overwrites same-named variable (or, in other words, same property of Variable object). This is because function declarations are instantiated after variable declarations, and are allowed to overwrite them
  • If we declare function via eval, that function should also replace that property’s attributes with its own. And since variables declared from within eval create properties without DontDelete, instantiating this new function should essentially remove existing DontDelete attribute from the property in question, making that property deletable (and of course changing its value to reference newly created function).
  • Unfortunately, this kind of spoofing doesn’t work in any implementation I tried. I might be missing something here, or this behavior might simply be too obscure for implementors to pay attention to
  • this.x = 1; delete x; // TypeError: Object doesn't support this action
  • var x = 1; delete this.x; // TypeError: Cannot delete 'this.x'
  • It’s as if variable declarations in Global code do not create properties on Global object in IE.
  • Not only is there an error, but created property appears to have DontDelete set on it, which of course it shouldn’t have:
  • “The global variable object is implemented as a JScript object, and the global object is implemented by the host.
  • Note how this and window seem to reference same object (if we can believe === operator), but Variable object (the one on which function is declared) is different from whatever this references.
  • delete doesn’t differentiate between variables and properties (in fact, for delete, those are all References) and really only cares about DontDelete attribute (and property existence).
  • The moral of the story is to never trust host objects.
  • Few restrictions are being introduced. SyntaxError is now thrown when expression in delete operator is a direct reference to a variable, function argument or function identifier. In addition, if property has internal [[Configurable]] == false, a TypeError is thrown:
Javier Neira

JQuery HowTo: Create callback functions for your jQuery plugins & extensions - 1 views

  • $.extend({  myFunc : function(someArg, callbackFnk){    // do something here    var data = 'test';     // now call a callback function    if(typeof callbackFnk == 'function'){      callbackFnk.call(this, data);    }  }});$.myFunc(someArg, function(arg){  // now my function is not hardcoded  // in the plugin itself  // and arg = 'test'});
  •  
    $.extend({ myFunc : function(someArg, callbackFnk){ // do something here var data = 'test'; // now call a callback function if(typeof callbackFnk == 'function'){ callbackFnk.call(this, data); } } }); $.myFunc(someArg, function(arg){ // now my function is not hardcoded // in the plugin itself // and arg = 'test' });
Javier Neira

JavaScript setTimeout Function - JavaScript Timing Events - 0 views

  •  
    JavaScript setTimeout Function - JavaScript Timing Events November 16, 2007 by Blogging Developer JavaScript features a couple of methods that lets you run a piece of JavaScript code (javascript function) at some point in the future. These methods are: * setTimeout() * setInterval() In this tutorial, I'll explain how setTimetout() method works, and give a real world example. You may find the details of setInterval() method in JavaScript setInterval Function - JavaScript Timing Events setTimeout() window.setTimeout() method allows you to specify a piece of JavaScript code (expression) will be run after specified number of miliseconds from when the setTimeout() method is called. Syntax var t = setTimeout ( expression, timeout ); The setTimeout() method returns a numeric timeout ID which can be used to refer the timeout to use with clearTimeout method. The first parameter (expression) of setTimeout() is a string containing a javascript statement. The statement could be a call to a JavaScript function like "delayedAlert();" or a statement like "alert('This alert is delayed.');". The second parameter (timeout), indicates the number of miliseconds to pass before executing the expression. Example An alert box will be shown 5 seconds later when you clicked the button. clearTimeout() Sometimes it's useful to be able to cancel a timer before it goes off. The clearTimeout() method lets us do exactly that. Its syntax is: clearTimeout ( timeoutId ); where timeoutId is the ID of the timeout as returned from the setTimeout() method call.
Javier Neira

Dynamically including Github code | PeterBraden.co.uk - 0 views

  •  
    /** * GitHub code inclusion * By Peter Braden */ var PBgithub = PBgithub || {}; /* You'll want to change these to your credentials */ PBgithub.login = "peterbraden"; PBgithub.token = "9d567812a941dc331cf4e431e7fc4ebc"; PBgithub.base = "http://github.com/api/v2/json/"; /** Load github content for this code element **/ PBgithub.codify= function(code_elem){ PBgithub.c = $(code_elem); $.getScript(PBgithub.make_url(PBgithub.base + 'repos/show/', "/branches", 'PBgithub.handle_branch')); } PBgithub.make_url = function(front, end, callback){ var data = "?callback=" + callback + "&login=" + PBgithub.login + "&token=" + PBgithub.token; return front + PBgithub.c.attr('username') + "/" + PBgithub.c.attr('repository') + end + data; } PBgithub.handle_file = function(data){ PBgithub.c.html( data['blob']['data'].replace(//g, '>')); PBgithub.next(); } PBgithub.handle_branch = function(data){ var branch = data['branches'][PBgithub.c.attr('branch')]; $.getScript(PBgithub.make_url(PBgithub.base + 'blob/show/', "/" + branch + "/" + PBgithub.c.attr('path'), 'PBgithub.handle_file')); } PBgithub.next = function(){ if (PBgithub.i < PBgithub.elems.length){ PBgithub.i+=1; PBgithub.codify(PBgithub.elems.get(PBgithub.i-1)); } } $(function(){ PBgithub.i = 0; PBgithub.elems = $('code.from-github'); PBgithub.next(); });
Javier Neira

Three map implementations in javascript. Which one is better? - Stack Overflow - 1 views

  • if (!Array.prototype.map) {&nbsp; Array.prototype.map = function(fun /*, thisp*/) &nbsp; {&nbsp; &nbsp; var len = this.length &gt;&gt;&gt; 0; &nbsp;// make sure length is a positive number&nbsp; &nbsp; if (typeof fun != "function") // make sure the first argument is a function&nbsp; &nbsp; &nbsp; throw new TypeError();&nbsp; &nbsp; var res = new Array(len); &nbsp;// initialize the resulting array&nbsp; &nbsp; var thisp = arguments[1]; &nbsp;// an optional 'context' argument&nbsp; &nbsp; for (var i = 0; i &lt; len; i++) {&nbsp; &nbsp; &nbsp; if (i in this)&nbsp; &nbsp; &nbsp; &nbsp; res[i] = fun.call(thisp, this[i], i, this); &nbsp;// fill the resulting array&nbsp; &nbsp; }&nbsp; &nbsp; return res;&nbsp; };}
  •  
    if (!Array.prototype.map) { Array.prototype.map = function(fun /*, thisp*/) { var len = this.length >>> 0; // make sure length is a positive number if (typeof fun != "function") // make sure the first argument is a function throw new TypeError(); var res = new Array(len); // initialize the resulting array var thisp = arguments[1]; // an optional 'context' argument for (var i = 0; i < len; i++) { if (i in this) res[i] = fun.call(thisp, this[i], i, this); // fill the resulting array } return res; }; }
Javier Neira

6 Advanced JavaScript Techniques You Should Know - 3 views

  • function showStatistics(args) { document.write("&lt;p&gt;&lt;strong&gt;Name:&lt;/strong&gt; " + args.name + "&lt;br /&gt;"); document.write("&lt;strong&gt;Team:&lt;/strong&gt; " + args.team + "&lt;br /&gt;"); if (typeof args.position === "string") { document.write("&lt;strong&gt;Position:&lt;/strong&gt; " + args.position + "&lt;br /&gt;"); } if (typeof args.average === "number") { document.write("&lt;strong&gt;Average:&lt;/strong&gt; " + args.average + "&lt;br /&gt;"); } if (typeof args.homeruns === "number") { document.write("&lt;strong&gt;Home Runs:&lt;/strong&gt; " + args.homeruns + "&lt;br /&gt;"); } if (typeof args.rbi === "number") { document.write("&lt;strong&gt;Runs Batted In:&lt;/strong&gt; " + args.rbi + "&lt;/p&gt;"); } } showStatistics({ name: "Mark Teixeira" }); showStatistics({ name: "Mark Teixeira", team: "New York Yankees" }); showStatistics({ name: "Mark Teixeira", team: "New York Yankees", position: "1st Base", average: .284, homeruns: 32, rbi: 101 });
  • Object-oriented JavaScript implements namespace-like principles due to the fact that properties and methods are declared inside of objects, thus there are less likely to be conflicts. A conflict could arise, however, through object names. And very likely, the conflict will occur "silently", thus you may not be alerted to the issue immediately.
  • if (typeof MY == "undefined") { MY = new Object(); MY.CUSTOM = new Object(); } MY.CUSTOM.namespace = function() { function showStatistics(args) { document.write("&lt;p&gt;&lt;strong&gt;Name:&lt;/strong&gt; " + args.name + "&lt;br /&gt;"); document.write("&lt;strong&gt;Team:&lt;/strong&gt; " + args.team + "&lt;br /&gt;"); if (typeof args.position === "string") { document.write("&lt;strong&gt;Position:&lt;/strong&gt; " + args.position + "&lt;br /&gt;"); } if (typeof args.average === "number") { document.write("&lt;strong&gt;Average:&lt;/strong&gt; " + args.average + "&lt;br /&gt;"); } if (typeof args.homeruns === "number") { document.write("&lt;strong&gt;Home Runs:&lt;/strong&gt; " + args.homeruns + "&lt;br /&gt;"); } if (typeof args.rbi === "number") { document.write("&lt;strong&gt;Runs Batted In:&lt;/strong&gt; " + args.rbi + "&lt;/p&gt;"); } } showStatistics({ name: "Mark Teixeira", team: "New York Yankees", position: "1st Base", average: .284, homeruns: 32, rbi: 101 }); } MY.CUSTOM.namespace();
  • ...1 more annotation...
  • Rendering Readable HTML
  •  
    //2. Object Literals to Pass Optional Arguments function showStatistics(args) { document.write("Name: " + args.name + "
    "); document.write("Team: " + args.team + "
    "); if (typeof args.position === "string") { document.write("Position: " + args.position + "
    "); } if (typeof args.average === "number") { document.write("Average: " + args.average + "
    "); } if (typeof args.homeruns === "number") { document.write("Home Runs: " + args.homeruns + "
    "); } if (typeof args.rbi === "number") { document.write("Runs Batted In: " + args.rbi + ""); } } showStatistics({ name: "Mark Teixeira" }); showStatistics({ name: "Mark Teixeira", team: "New York Yankees" }); showStatistics({ name: "Mark Teixeira", team: "New York Yankees", position: "1st Base", average: .284, homeruns: 32, rbi: 101 }); //Using Namespaces to Prevent Conflicts if (typeof MY == "undefined") { MY = new Object(); MY.CUSTOM = new Object(); } MY.CUSTOM.namespace = function() { function showStatistics(args) { .................. } showStatistics({ name: "Mark Teixeira", team: "New York Yankees", position: "1st Base", average: .284, homeruns: 32, rbi: 101 }); } MY.CUSTOM.namespace();
Vincent Tsao

Javascript Closures - 0 views

  • The simple explanation of a Closure is that ECMAScript allows inner functions; function definitions and function expressions that are inside the function bodes of other functions. And that those inner functions are allowed access to all of the local variables, parameters and declared inner functions within their outer function(s).
Javier Neira

Inheritance Patterns in JavaScript - 2 views

  •  
    This article discusses the advantages of the pseudoclassical pattern over the functional pattern. I argue that the pattern used by the Closure Library paired with the Closure Compiler removes existing hazards while I also examine the hazards introduced by the functional pattern (as defined in The Good Parts). First let me demonstrate what I mean by the functional pattern.
Javier Neira

Caffeinated Simpleton » Blog Archive » An Introduction to JavaScript's "this" - 2 views

  • That’s what this is expected to be, anyway. It’s expected to be a reference to the current instance of whatever object it’s defined within.
  • It’ll give an error saying that this doesn’t have a member called condiments, even though it clearly does. What happened?!
  • This is because there is no binding of functions to instances in JavaScript.
  • ...3 more annotations...
  • The setTimeout function, however, just has a reference to that function. When it calls it, it’s not aware of myHotDog, so JavaScript sets this to window
  • function HotDog() { var my = this; // my references the current this, which is correct. my.condiments = "mustard, ketchup"; my.getCondiments = function() { return my.condiments; //my is guaranteed to be a reference to the original "this" } }
  • In constructors, this is always your instance. So we created a new variable, my, that references the HotDog instance. This allows you to always refer to the HotDog instance, no matter how the getCondiments function is called.
Javier Neira

Bind Multiple Controls to a Single Event in jQuery - 0 views

  •  
    Multiple Elements Single Event
yc c

Color Picker - Raphaël - 0 views

shared by yc c on 04 Mar 10 - Cached
  •  
    No images. No libraries*. Works even in IE6. // Color Picker by Raphaël - raphaeljs.com var icon = Raphael("picker", 23, 23).colorPickerIcon(11, 11, 10); icon.attr({cursor: "pointer"}).node.onclick = function () {    document.getElementById("benefits").style.visibility = "visible";    var out = document.getElementById("output");    out.style.visibility = "visible";                   // this is where colorpicker created    var cp = Raphael.colorpicker(document.body.offsetWidth / 2 - 150, 250, 300, "#eee", document.getElementById("picker2"));                   out.onkeyup = function () {        cp.color(this.value);    };    // assigning onchange event handler    cp.onchange = function (clr) {        out.value = clr;        document.body.style.background = clr;        document.body.style.color = Raphael.rgb2hsb(clr).b s it. Too easy                    icon.node.onclick = null;}; 
Javier Neira

InfoQ: ECMAScript 5 released - 1 views

  • The introduction of strict mode aims to avoid common coding problems in ECMAScript applications. This is achieved with the presence of a lone string literal in a unit (script or function): "use strict;"
  • for either the entire script (if at the top of the script) or for a single function (if the first part of a function).
  • var i=3 is needed
  • ...10 more annotations...
  • and introducing new variables through eval cannot occu
  • delete cannot be used against arguments, functions or variables or other properties with the configurable flag set to false
  • with statements, often a source of errors, are no longer used and considered syntax errors
  • Functions can no longer have duplicate arguments with the same name Objects can no longer have duplicate properties with the same name
  • Access to the global object becomes a runtime error
  • A new JSON object with parse and stringify to support efficient generation of JSON data; like eval but without the security implications of being able to reduce code
  • Array now has standard functions, such as indexOf(), map(), filter(), and reduce()
  • Object now has seal()
  • and freeze()
  • Object.getPrototypeof() returns the prototype of the given object
yc c

Underscore.js - 4 views

  •  
    Underscore is a utility-belt library for Javascript that provides a lot of the functional programming support that you would expect in Prototype.js (or Ruby), but without extending any of the built-in Javascript objects. It's the tie to go along with jQuery's tux.
  •  
    Underscore is a utility-belt library for JavaScript that provides a lot of the functional programming support that you would expect in Prototype.js (or Ruby), but without extending any of the built-in JavaScript objects. It's the tie to go along with jQuery's tux. Collections each, map, reduce, detect, select, reject, all, any, include, invoke, pluck, max, min, sortBy, sortedIndex, toArray, size Arrays first, last, compact, flatten, without, uniq, intersect, zip, indexOf, lastIndexOf Functions bind, bindAll, delay, defer, wrap, compose Objects keys, values, extend, clone, isEqual, isElement, isArray, isFunction, isUndefined Utility noConflict, identity, uniqueId, template
Javier Neira

The difference between 'return false;' and 'e.preventDefault();' | The Hostma... - 2 views

  •  
    function() { return false; } // IS EQUAL TO function(e) { e.preventDefault(); e.stopPropagation(); }
Javier Neira

Michael Sharman - chapter31 » Including js files from within js files - 1 views

  •  
    01.//this function includes all necessary js files for the application 02.function include(file) 03.{ 04. 05. var script = document.createElement('script'); 06. script.src = file; 07. script.type = 'text/javascript'; 08. script.defer = true; 09. 10. document.getElementsByTagName('head').item(0).appendChild(script); 11. 12.} 13. 14./* include any js files here */ 15.include('js/myFile1.js'); 16.include('js/myFile2.js');
Javier Neira

Understanding JavaScript Timers « JavaScript, JavaScript - 1 views

  • By enforcing a timeout (however small) you remove the function from the current execution queue and hold it back until the browser is not busy.
  • you can make long running functions (on which no other immediate function is dependent) defer execution until more urgent routines have completed.
  • The firing of the setTimeout callback is asynchronous, the function itself will be invoked in line and after the current invocation queue
Javier Neira

The Dark side of JavaScript - Part 2 @ Milkshake Systems - 1 views

  • In JavaScript, where functions are objects and aren’t declared as part of anything, the object referenced by this is called the function context and is determined by how the function is invoked not by how its declared.
  • This means that the same function can have different contexts depending on which object calls it.
anonymous

Underscore.js - 3 views

  •  
    Underscore is a utility-belt library for JavaScript that provides a lot of the functional programming support that you would expect in Prototype.js (or Ruby), but without extending any of the built-in JavaScript objects. It's the tie to go along with jQuery's tux, and Backbone.js's suspenders.
yc c

JavaScript Shell - 0 views

  •  
    Features: You can enter statements and expressions at the same prompt. The result of each non-void statement or expression is shown. User-defined variables. b = document.body User-defined functions. function f() { return 5; } JavaScript error messages are shown in red. Previous statements and expressions are available through Up and Down arrow keys. Tab completion. Multiline input (Shift+Enter to insert a line break). If the shell is opened using a bookmarklet, JavaScript typed into the shell runs in the context of the original window. Works well in Firefox, mostly works in Opera 8 and in IE 6 for Windows. Suggested uses: Test short bits of JavaScript, bookmarklets, or user scripts. (For longer bits of JavaScript, try the JavaScript development enviornment too.) Explore DOM objects such as document.body using props (Alt+P) to figure out what is possible. Explore the DOM of a specific page using the bookmarklet version of the shell. Modify the DOM of a specific page using the bookmarklet version of the shell. Use the shell like you would use the home screen of a calculator such as a TI-83. Alt+M gives you easy access to math functions such as sin and pow.
1 - 20 of 51 Next › Last »
Showing 20 items per page