Skip to main content

Home/ javascript/ Group items tagged code

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

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
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

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.
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

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

Google Closure: How not to write JavaScript - 3 views

  • “It’s a JavaScript library written by Java developers who clearly don’t get JavaScript.”
  • Unfortunately, unlike the built-in properties supplied by Object.prototype, custom properties added to Object.prototype will show up as an object property in any for-in loop in the page.
  • custom properties added to
  • ...3 more annotations...
  • will show up as an object property in any
  • loop in the page.
  • var&nbsp;a&nbsp;=&nbsp;"I&nbsp;am&nbsp;a&nbsp;string!"; &nbsp; 2 alert(typeof&nbsp;a);&nbsp;//&nbsp;Will&nbsp;output&nbsp;"string" &nbsp; 3 var&nbsp;b&nbsp;=&nbsp;new&nbsp;String("I&nbsp;am&nbsp;also&nbsp;a&nbsp;string!"); &nbsp; 4 alert(typeof&nbsp;b);&nbsp;//&nbsp;Will&nbsp;output&nbsp;"object"&nbsp;
Ivan Pavlov

Graphic JavaScript Tree with Layout - 0 views

  • This article presents a JavaScript component which renders a tree on the screen using VML (Vector Markup Language) in Internet Explorer 6+ or the &lt;canvas&gt; element in Firefox 1.5+.
Mike Chelen

JavaScript & MySQL With Jaxer - 0 views

  •  
    Wouldn't it be cool if you could work with MySQL within your JavaScript code? Think about it, you wouldn't have to spend extra time writing extra server-side code for connecting to, querying, and parsing results, you could just write a little bit more code in your JavaScript and be done with it. Of course, we wouldn't want any of this SQL exposed to the end-user, as that would be a major security issue, but what if that problem was solved as well? You might also raise the point that you'd still need the ability to prepare your SQL statements that take dynamic input to prevent SQL injection attacks, but if that weren't an issue, wouldn't that be awesome as well?
yc c

Bookmarklet Coding › Left Logic - 0 views

  • if you want your bookmarklet to work in all browsers, it has to adhere to length limits: IE 5 - 2084 bytes IE 6 - 508 bytes IE 6 SP 2 - 488 bytes IE 7 - 2084 bytes Firefox + Safari - &gt; 2000 bytes IE6 has the smallest length, and that includes the javascript: pseudo protocol.
  • Avoid the double quote character ("). Since the user is going to install your bookmarklet from a link, it will be wrapped with quotes (assuming xhtml). If you absolutely require quotes, try using the entity: %22
  •  
    if you want your bookmarklet to work in all browsers, it has to adhere to length limits: * IE 5 - 2084 bytes * IE 6 - 508 bytes * IE 6 SP 2 - 488 bytes * IE 7 - 2084 bytes * Firefox + Safari - > 2000 bytes IE6 has the smallest length, and that includes the javascript: pseudo protocol.
yc c

Closure Compiler - Google Code - 1 views

  •  
    The Closure Compiler is a tool for making JavaScript download and run faster. It is a true compiler for JavaScript. Instead of compiling from a source language to machine code, it compiles from JavaScript to better JavaScript. It parses your JavaScript, analyzes it, removes dead code and rewrites and minimizes what's left. It also checks syntax, variable references, and types, and warns about common JavaScript pitfalls.
yc c

JS Bin - Collaborative JavaScript Debugging - 1 views

shared by yc c on 30 Jan 10 - Cached
  •  
    specifically designed to help JavaScript and CSS folk test snippets of code, within some context, and debug the code collaboratively. JS Bin allows you to edit and test JavaScript and HTML (reloading the URL also maintains the state of your code - new tabs doesn't). Once you're happy you can save, and send the URL to a peer for review or help. They can then make further changes saving anew if required.
Ivan Pavlov

Monads on the Cheap I: The Maybe Monad at Oliver Steele - 0 views

  • What about the case where most products don’t have offerings, or the offerings don’t have merchants, vel cetera? If this were a frequent case, and this were inner-loop code, I might introduce a global empty object in order to reduce the object instantiation overhead (which happens right away) and the GC load (which shows up over time). E.g. define var $N={}, and use: var product = ..., merchantName = (((product||$N).offering||$N).merchant||$N).name; if (merchantName) displayMerchantName(merchantName);
yc c

Web development and deployment tools: CodeRun - 1 views

  •  
    Build-time error reporting, refactoring and code completion in Visual Studio Extended JavaScript syntax power with C# language features Pure client-side control library coded in C#
yc c

Shell Editor | MooShell | to test your JavaScript code - 1 views

shared by yc c on 30 Jan 10 - Cached
  •  
    MooShell is a shell editor where you can write your JavaScript, HTML and CSS code and run it. It might prove to be useful in various cases where you need to test your code without reloading your browser.
Mr. DiGi

Google Code Blog: Introducing Closure Tools - 1 views

  • Closure Compiler is a JavaScript optimizer that compiles web apps down into compact, high-performance JavaScript code.
  • Closure Library&nbsp;is a broad, well-tested, modular, and cross-browser JavaScript library. Web developers can pull just what they need from a wide set of reusable UI widgets and controls, as well as lower-level utilities for the DOM, server communication, animation, data structures, unit testing, rich-text editing, and much, much more. (Seriously. Check&nbsp;the docs.)
  • Closure Templates&nbsp;grew out of a desire for web templates that are precompiled to efficient JavaScript. &nbsp;Closure Templates have a simple syntax that is natural for programmers.
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.
Julian Knight

JavaScriptTemplates - trimpath - Google Code - 0 views

  •  
    Code HTML from client side javascript using a simple template language that can be stored in a textarea
yc c

CodeRun - Online IDE - 2 views

  •  
    Develop ASP.NET, php and Ajax applications in your browserTest and debug code in the cloudInstantly deploy applications to the cloudDiscover and share code
yc c

HTML & JavaScript Encoder/Decoder - 1 views

  •  
    Encoding/Decoding Escape/Unescape These scripts are intended to explain how to "hide" HTML and/or javascript from other people who view your page's source code. It is not foolproof, but it does make it more difficult to read and understand the source code. Due to the nature of how these scripts work, the explanation may seem complicated and drawn out, but be patient and it should make sense once you gain a little experience with them. You don't really have to know the ins-and-outs of these scripts, but it does help you understand how and why they work. So, take a seat and I'll do my best to make this seem as un-complicated as possible.
1 - 20 of 88 Next › Last »
Showing 20 items per page