Skip to content

Instantly share code, notes, and snippets.

@erikeldridge
Created March 17, 2011 07:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erikeldridge/873978 to your computer and use it in GitHub Desktop.
Save erikeldridge/873978 to your computer and use it in GitHub Desktop.
Playing with prototypal inheritance in JavaScript
// I'm not sure what this is supposed to be demonstrating,
// but I think it's worth noting that flashyBlueBtn contains
// color & effect attributes event though we say
// FlashyBlueButton.prototype = blueBtn.
function Button(color){
this.color = color;
}
var blueBtn = new Button('blue');
function FlashyBlueButton(effect){
this.effect = effect;
}
FlashyBlueButton.prototype = blueBtn;
var flashyBlueBtn = new FlashyBlueButton('blink');
console.log(flashyBlueBtn.color, flashyBlueBtn.effect);
//Calling a parent's constructor inside the child's to obtain the parent's attributes
function Parent(attr1){
this.attr1 = attr1;
}
function Child(attr1, attr2){
this.prototype = Parent.apply(this, [attr1]);
this.attr2 = attr2;
}
var child = new Child('green', 'red');
// Credit http://developer.yahoo.com/yui/3/examples/yui/yui-extend.html
function Bird(name) {
this.name = name;
}
Bird.prototype.flighted = true;
Bird.prototype.isFlighted = function () { return this.flighted };
Bird.prototype.getName = function () { return this.name };
function Chicken(name) {
Chicken.superclass.constructor.call(this, name);
}
Y.extend(Chicken, Bird);
Chicken.prototype.flighted = false;
// Credit https://github.com/yui/yui3/blob/master/src/oop/js/oop.js#L156-183
Y.extend = function(r, s, px, sx) {
var sp = s.prototype, rp = Y.Object(sp);
r.prototype = rp;
rp.constructor = r;
r.superclass = sp;
if (s != Object && sp.constructor == OP.constructor) {
sp.constructor = s;
}
return r;
}
// Credit https://github.com/yui/yui3/blob/master/src/yui/js/yui-object.js
var F = function() {},
O = function(o) {
F.prototype = o;
return new F();
},
Y.Object = O;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment