Created
April 29, 2011 23:42
-
-
Save robotlolita/949239 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var obj = function() { | |
// local variables, since a function creates a new scope binding, they can only | |
// be acessed inside this function (and any function that is defined inside this function) | |
var x = 1, y = 2 | |
// The return value is anything you want exposed to the outside world, that will | |
// be referenced by `obj'. You could also return a primitive here, instead of an object | |
return { sum: function() { return x + y }} | |
}() | |
console.log('obj.sum():', obj.sum()) // 3 | |
console.log('"x" in obj:', 'x' in obj) // false | |
// constructor are something entirely different. They allow you to construct object | |
// that are based on the top of other objects (inheritance), and also to initialize | |
// this object somehow. | |
// | |
// For a huge amount of time, this was the only way of doing inheritance in JS. But | |
// ECMAScript 5 introduces the new `Object.create', which allows you to create objects | |
// and define their inheritance without the need of a constructor. | |
function Obj() { | |
// These are properties patched directly in the object, and thus acessible by anyone | |
// who have a reference to this object. | |
this.x = 1 | |
this.y = 2 | |
} | |
Obj.prototype = Array.prototype // Makes Obj inherit the properties defined in Array.prototype | |
Obj.prototype.sum = function(){ return this.x + this.y } | |
var x = new Obj // creates a new Obj, which will inherit everything defined in Array.prototype | |
console.log('"x" in x', 'x' in x) // true | |
console.log('x.sum():', x.sum()) // 3 | |
// On ECMAScript 5, that would be the same as: | |
var x = Object.create(Array.prototype, {sum: {value: function(){ return this.x + this.y }}}); | |
x.x = 1 | |
x.y = 2 | |
console.log('x.sum() [with Object.create]:', x.sum()) // 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment