Skip to main content

Home/ javascript/ Group items tagged this

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

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

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

  • 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;  };}
  •  
    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; }; }
mesbah095

Guest Post Online - 0 views

  •  
    Article Writing & Guestpost You Can Join this Site for Your Article & guest post, Just Easy way to join this site & total free Article site. This site article post to totally free Way. Guest Post & Article Post live to Life time only for Current & this time new User. http://guestpostonline.com
qualitypoint Tech

Arts Point - Web Application for connecting Artists, Promoters and Viewers of Live Musi... - 1 views

  •  
    This Arts Point script is useful for connecting Promoters, Artists and Viewers of Live Music Events. Promoters can advertise about their Live music events in this application, and Artists can apply for any event of their choice. The promoters can choose suitable Artists for their Events. The viewers can search their favorite live music events easily.
yc c

ColorPicker 0.6 - 0 views

  •  
    This colorPicker is a light weight all-rounder (only ~46k incl. all 16 files) that can display and let you choose the entire color palette (~16.78 mil. colors) in 6 different color modes (+3 extra modes in RGB). This highly customizable and easy to install app comes in 4 different sizes (from 151 x 87 pixels to 405 x 302 pixels) and therefore different feature levels so you can use it for every supposable cause from 'easy choice' to 'professional determination'. That's probably all you'll ever need to let your clients choose the right color.
Mike Chelen

OpenSocial Dev App - 0 views

  •  
    This OpenSocial application provides the ability to write and save JavaScript code samples to execute against OpenSocial containers. This helps rapidly test sample OpenSocial code. Code samples can be saved and loaded. You can give other developers links to code samples for instructional or debugging purposes.
Javier Neira

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

  •  
    Multiple Elements Single Event
Bartłomiej Małysz

Galleriffic | flickr like jQuery web gallery script - 0 views

  •  
    Galleriffic was inspired by Mike Alsup's Cycle plugin, but with performance in mind for delivering a high volume of photos. This is my first experiment with jQuery, so I would love feedback on how to improve this plugin. I am not so great at spelling, and it was much later that I realized that the more appropriate spellings would be Gallerific or Gallerrific, but is too late now for a name change, so Galleriffic remains.
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

How To Make Firebug's JavaScript Debugger Break Inside Dynamic JavaScript Using The 'de... - 0 views

  • The Problem With Dynamic JavaScript However, what if the JavaScript file where you need to set breakpoints is not static but instead dynamic (generated on the fly). If you set a breakpoint in this case and reload the page, the breakpoint will most likely disappear, especially if the JavaScript url is generated uniquely every time. The Solution If you have access to the source, the solution comes in the form of the debugger; keyword. Just add it to your dynamic JavaScript generator or into any JavaScript file you have access to exactly where you want Firebug to break, and voila – it does.
  • More so, this method also works in Google Chrome and IE (if you have Microsoft Script Debugger)
  •  
    The Problem With Dynamic JavaScript However, what if the JavaScript file where you need to set breakpoints is not static but instead dynamic (generated on the fly). If you set a breakpoint in this case and reload the page, the breakpoint will most likely disappear, especially if the JavaScript url is generated uniquely every time. The Solution If you have access to the source, the solution comes in the form of the debugger; keyword. Just add it to your dynamic JavaScript generator or into any JavaScript file you have access to exactly where you want Firebug to break, and voila - it does.
yc c

Sizzle JavaScript Selector Library - 1 views

shared by yc c on 30 Jan 10 - Cached
  •  
    A pure-JavaScript CSS selector engine designed to be easily dropped in to a host library. Sizzle supports virtually all CSS 3 Selectors - this even includes some parts that are infrequently implemented such as escaped selectors (".foo\\+bar"), Unicode selectors, and results returned in document order. There are a few notable exceptions to the CSS 3 selector support (the reasoning for this decision can be found here): * :root * :target * :nth-last-child * :nth-of-type / :nth-last-of-type / :first-of-type / :last-of-type / :only-of-type * :lang() In addition to the CSS 3 Selectors Sizzle supports the following additional selectors or conventions.
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.
Muhammad Saqib

Why Do You Need a Mobile Website Design or Responsive Web Design - 0 views

  •  
    According to a recent article on Huffington’s post, the U.N telecom agency stated that there are more than 6 billions mobile devices. Out of them, 1.2 billions users use web-enabled mobile phones worldwide & this usage of mobile is growing at astounding rate, being adapted by every family. We have seen a significant increase in the mobile users in the past three years & this global trend is surely continuing to see growth in upcoming years. What does this mean to a web designer & site owner? It underlines the importance of a company to have a mobile version of their business website.
Hussain M Elius

Better Coda Slider - 0 views

  • This technique demonstrates an accessible 'Coda'-like slider interface, but in addition, allows you to place links to the sliding content anywhere on the page and have the effect (and navigation) still work.
  •  
    This technique demonstrates an accessible 'Coda'-like slider interface, but in addition, allows you to place links to the sliding content anywhere on the page and have the effect (and navigation) still work.
Ivan Pavlov

Jeene: An automatic partial evaluator for JavaScript - 0 views

  • The purpose of this posting is to show that is is possible to create an online partial evaluator for JavaScript, written also in JavaScript. As far as I know, this has been not been done before. This post is the first in a series describing the inner workings of Jeene.
Javier Neira

JavaScript EE, Part 1: Run JavaScript files on the server side - 0 views

  • freedom to use the same JavaScript routines on both servers and clients. In addition, the techniques presented throughout this series will allow you to maintain a single code base for both Ajax and non-Ajax clients
  • This double-coding issue can be avoided by using JavaScript combined with Java code on the server side, getting full support of scripting languages through the javax.script API. In addition, the Java SE Development Kit (JDK) 6 already includes Mozilla's Rhino JavaScript engine, which means no setup is required.
  • the toSource() method, which all JavaScript objects must have.
  • ...5 more annotations...
  • engine.eval(scriptReader, vars);
  • sun.org.mozilla.javascript.internal.NativeObject
  • all data exchange between the Java code and the executed script should be done through primitive variables, strings, and Java objects (for example, beans) whose properties and methods can be accessed very easily in the JavaScript code. Simply said, don't try to access native JavaScript objects in your Java code. Use Java objects in the JavaScript code instead.
  • Note that javax.script.Invocable is an optional interface, which some script engines may not implement. The JavaScript engine that comes with JDK 6 does support this interface.
  • you can significantly reduce the execution time by compiling the scripts, using the methods provided by another optional interface named javax.script.Compilable, which is supported by the JavaScript engine of JDK 6.
qualitypoint Tech

PHP Quiz Questions and Answers - 1 views

  •  
    You can attend our Quiz here.\n\nWe are working on to publish more questions in many topics (e.g mysql, javascript, html,...).\n\nSo, you can bookmark this blog for further reading, or you can subscribe to our blog feed.
  •  
    I don't understand why you saved this to the javascript group...
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.
Javier Neira

fingernails in oatmeal, Metaprogramming: Ruby vs. Javascript - 0 views

  • drew['battleCry']();
  • What we want is the ability to define a method dynamically (given a name) that is also a closure over the lexical scope at the point of method definition.
  • color_name = 'black'&nbsp;Ninja.send(:define_method, 'color') do&nbsp;&nbsp;puts "#{name}'s color is #{color_name}"end
  • ...5 more annotations...
  • var colorName = "black";&nbsp;Ninja.prototype['color'] = function () {&nbsp;&nbsp;puts(this.name + "'s color is " + colorName);}
  • The ubiquity of closures in Javascript is extremely powerful and, as we have seen so far, makes metaprogramming very easy.
  • You can think of a metaclass as a class definition specific to a single instance of a class.
  • This means we can add methods to an object’s metaclass without adding the same behavior to all instances of that object’s class.
  • This means that Javascript does not distinguish between classes/prototypes and instances and, therefore, we can add our desired behavior directly to the instance.
1 - 20 of 78 Next › Last »
Showing 20 items per page