Skip to content

Instantly share code, notes, and snippets.

@niyazpk
niyazpk / gist:634237
Created October 19, 2010 13:59
Better JS programs
tips.push({
author: 'your_twitter_handle',
message: 'Your Tip Message',
WrongWay: [
'<div>',
' Code Example',
'</div>'
],
RightWay: [
'<div>',
@niyazpk
niyazpk / gist:636361
Created October 20, 2010 12:54
Simple url shortener bookmarklet
javascript:(function() {
/* Replace login and apiKey, get your's from http://bit.ly/a/your_api_key */
var login="xxxxxxxxx",
apiKey="R_xxxxxxxx",
otherlib=false;
if (typeof jQuery=='undefined' && typeof $=='function') {
otherlib=true;
}
function getScript(url,success){
var script=document.createElement('script');
@niyazpk
niyazpk / gist:1460215
Created December 11, 2011 12:01
Get, set & delete in JavaScript
// get
object.name
object[expression]
// set
object.name = value;
object[expression] = value;
// delete
delete object.name
var my_object = {foo: bar}; // object literals are a good part of JavaScript
// the above is equallant to the following code in ES5
// Notice that a lot of internals are exposed
var my_object = Object.defineProperties(
Object.create(Object.prototype), {
foo: {
value: bar,
writable: true,
enumerable: true,
// You can override and the getters and setters
Object.defineProperty(my_object, 'inch',{
get : function() { return this.mm / 25.4; },
set : function(value) { this.mm = value * 25.4; },
enumerable: true
});
Car car = new Car(); // Redundancy
// objects have a prototype attribute
Object.create(object, properties)
Object.getPrototypeOf(object) // you probably should not use this
// The following will fail if word ==== 'constructor' ...
function bump_count(word) {
if(word_count[word]){
word_count[word] += 1;
}else{
word_count[word] = 1;
}
}
// The following code will fix the problem
function bump_count(word) {
if(typeof word_count[word] === 'number'){
word_count[word] += 1;
}else{
word_count[word] = 1;
}
}
// An easy fix would be:
for (name in object){
if (object.hasOwnProperty(name)){
// do stuff
}
}
// The above will fail if the object has a hasOwnProperty property.