Skip to content

Instantly share code, notes, and snippets.

View gsans's full-sized avatar
🚁
Hawaii is Awesome

Gerard Sans gsans

🚁
Hawaii is Awesome
View GitHub Profile
<!-- this is set to the DOM element -->
<a href="#" class="myclass another" id="1" onclick="alert(this.id + ' ' + this.className)">DOM element</a>
function Fn(a, b) { return a + b + this; };
// implicit this = 1
console.log(Fn.call(1, 2, 3)); //6
console.log(Fn.apply(1, [2, 3])); //6
//note: if null is passed this = window
//constructor function
function Person(id) {
//new keyword implicit this = {};
this.id = id;
//new keyword implicit return this;
};
//this points to new object
var person = new Person(1);
// object scope
var scope = {
number: 7,
Fn: function() {
return this.number;
}
};
// this points to scope (not window)
console.log(scope.Fn()); // 7
var number = 7;
console.log(this.number === window.number); // true
another = 8; // global variable
console.log(this.another === window.another); // true
//within a function this is set to window
function Fn() {
return this;
};
//creation separated from initialisation
var order = {};
order.id = 1;
order.customer = {}; //ups I did it again
order.customer.id = 1;
//creation and initialisation together
var order = {
id: 1,
customer: {
id: 1
}
};
//Using standard function definition
//note: convention is to use initial capital letter
function Order(id) {
//new keyword implicit code: var this = {};
this.id = id;
//implicit: return this;
};
var order = new Order(1);
//Using an anonymous function reference
var Order = function(id) {
//new keyword implicit code: var this = {};
this.id = id;
//implicit: return this;
};
var order = new Order(1);
//Using a new object
var Order = function(id) {
//we ignore ‘this’ altogether… it’s evil right?
var that = {};
that.id = id;
return that;
};
var order = new Order(1);