SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Member
    Join Date
    Dec 2010
    Posts
    16
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    JavaScript - Inheritance Question

    I'm curious if anyone would, or does use something along the lines of extend2 for inheritance. Here's a quick demo of how it works:
    Code JavaScript:
    var extend2 = function(Child, Parent) {
    	var p = Parent.prototype, c = Child.prototype, i;
     
    	for (i in p) {
    		c[i] = p[i];
    	}
     
    	c.uber = p;
    };
     
    // A Constructor
    var A = function() {
    	this.name = "A";
    	this.holler = "A";
    	this.foo.constr = this;
    };
    // Augment
    A.prototype.foo = {
    	init: function() {
    		// Empty for now
    	},
    	ok: "A ok"
    };
     
    // B Constructor
    var B = function() {
    	this.name = "B";
    	this.holler = "B";
    	this.foo.constr = this;
    };
    // Inheritance
    extend2(B, A);
    // Augment
    B.prototype.foo = {
    	init: function() {
    		// Empty for now
    	},
    	ok: "B ok"
    };
     
    // C Constructor
    var C = function() {
    	this.name = "C";
    	this.holler = "C";
    	this.foo.constr = this;
    };
    // Inheritance
    extend2(C, B);
    // Augment
    C.prototype.foo = {
    	init: function() {
    		var constr = this.constr;
     
    		console.log(constr.uber.uber.foo.ok);
    	},
    	ok: "C ok"
    };
     
    // Invoke
    var fooA = new A();
    fooA.foo.init();
     
    var fooB = new B();
    fooB.foo.init();
     
    var fooC = new C();
    fooC.foo.init();

    If the mentioned approach is problematic, or another approach is more looked upon - let me know, thanks.

  2. #2
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,716
    Mentioned
    103 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by domscripter View Post
    I'm curious if anyone would, or does use something along the lines of extend2 for inheritance.
    Yes, it's Object.create() in newer versions of JavaScript.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  3. #3
    SitePoint Member
    Join Date
    Dec 2010
    Posts
    16
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •