Created
December 22, 2011 04:44
-
-
Save adomokos/1508947 to your computer and use it in GitHub Desktop.
A couple of ways to create JS objects
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
// From the book - Javascript: The Good Parts. | |
// Differential Inheritance | |
var myMammal = { | |
name: 'Herb the Mammal', | |
getName: function() { | |
return this.name; | |
}, | |
says: function() { | |
return this.saying || ''; | |
} | |
}; | |
var myCat = Object.create(myMammal); | |
myCat.name = 'Henrietta'; | |
myCat.saying = 'meow'; | |
myCat.purr = function(n) { | |
var i, s = ''; | |
for (i = 0; i < n; i += 1) { | |
if (s) { | |
s += '-'; | |
} | |
s += 'r'; | |
} | |
return s; | |
}; | |
myCat.getName = function() { | |
return this.says() + ' ' + this.name + ' ' + this.says(); | |
}; | |
//var myCat = new Cat('Henrietta'); | |
var says = myCat.says(); // 'meow' | |
//console.log(says); | |
var purr = myCat.purr(5); | |
//console.log(purr); | |
var name = myCat.getName(); | |
//console.log(name); | |
// 3 ways to create objects | |
// 1) Object literal | |
// 2) Calling new on a function | |
// 3) Object.create | |
// | |
// 4) Functional object creation | |
var mammal = function(spec) { | |
var that = {}; | |
that.getName = function() { | |
return spec.name; | |
}; | |
that.says = function() { | |
return spec.saying || ''; | |
}; | |
return that; | |
}; | |
var myMammal = mammal({name: 'Herb'}); | |
var cat = function(spec) { | |
spec.saying = spec.saying || 'meow'; | |
var that = mammal(spec); | |
that.purr = function(n) { | |
var i, s = ''; | |
for (i = 0; i < n; i += 1) { | |
if (s) { | |
s += '-'; | |
} | |
s += 'r'; | |
} | |
return s; | |
}; | |
that.getName = function() { | |
return this.says() + ' ' + spec.name + ' ' + this.says(); | |
}; | |
return that; | |
} | |
var myCat = cat({name: 'Henrietta'}); | |
var says = myCat.says(); // 'meow' | |
//console.log(says); | |
var purr = myCat.purr(5); | |
//console.log(purr); | |
var name = myCat.getName(); | |
//console.log(name); | |
// Calling parent object's method | |
// This does not work under node.js | |
//Object.method('superior', function(name) { | |
//var that = this, | |
//method = that[name]; | |
//return function() { | |
//return method.apply(that, arguments); // some metaprogramming magic | |
//}; | |
//}); | |
var coolCat = function(spec) { | |
var that = cat(spec), | |
superGetName = that.getName(); | |
that.getName = function(n) { | |
return 'like ' + superGetName + ' baby'; | |
}; | |
return that; | |
} | |
var myCoolCat = coolCat({name: 'Bix'}); | |
console.log(myCoolCat.getName()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment