Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this do?

Tags:

javascript

I found this. What does it do?

function G(a, b) {
  var c = function() { };
  c.prototype = b.prototype;
  a.T = b.prototype;
  a.prototype = new c;
}
  • It looks very similar to Crockford's Prototypal Inheritance in JavaScript.
  • Stackoverflow: What is happening in Crockford’s object creation technique?.
like image 856
TJR Avatar asked Nov 14 '22 10:11

TJR


1 Answers

It looks similar to the Crockford's Object.create method, but this function is used to "setup" constructors.

It accepts two constructors as arguments, and it setups the prototype of the first one.

Let me rename the cryptic variable names:

function G(sub, super) {
  var F = function() { };
  F.prototype = super.prototype;
  sub.superLink = super.prototype;
  sub.prototype = new F();
}

function Super () {
  //...
}
Super.prototype.member1 = 'superMember1';

function Sub() {
  this.member2 = 'subMember2';
}

G(Sub, Super);

new Sub(); // Object { member2="subMember2",  member1="superMember1"}

Edit: The T property is simply used to know what is the "super" constructor of the sub one, I've seen this pattern on other places, like in the book Pro JavaScript Design Patterns (page 43), with some additions, to prevent the constructor property to point to the wrong object:

function extend(subClass, superClass) {
    var F = function() {};
    F.prototype = superClass.prototype;
    subClass.prototype = new F();
    subClass.prototype.constructor = subClass;

    subClass.superclass = superClass.prototype;
    if(superClass.prototype.constructor == Object.prototype.constructor) {
        superClass.prototype.constructor = superClass;
    }
}

See also:

  • JavaScript inheritance extend function
like image 102
Christian C. Salvadó Avatar answered Dec 20 '22 22:12

Christian C. Salvadó