Javascript's super constructor - clarification

2019-07-12 20:15发布

I've been watching this video where Damian said that Crockford called it :" super constructor pattern"

Code sample : ( from the video)

var signalR;

signalR = function (url){
 return new signalR.prototype.init(url);
}

signalR.prototype={
 init:function(url)
 {
   this.url=url;
 } 
}

signalR.prototype.init.prototype = signalR.prototype;

Now, I've googled about Crockford and super constructor but all I could find is the implementation of Object.create :

Which I understand pretty clear : ( also it's gotchas)

function create(o)
{
 function f(){};
 f.prototype=o;
 return new f();
}

But still I don't see how it relates :

Question :

  • What exactly (in the video) - did he try to solve by using this pattern? ( also small code sample will be much appreciated).

1条回答
混吃等死
2楼-- · 2019-07-12 21:06

Lets see at normal class with constructor and prototype

//-------------------
//---- Class signalr
//-------------------

//-- constructor
var signalr=function () {}

//--prototype
signalr.prototype.init=function (url)
    {
    this.url=url;
    }

signalr.prototype.test=function () {alert ("test");}

//-------------------
//---- Class signalr -- END
//-------------------

so to generate a new instance of this class we have to write the following.

var con=new signalr ();  //--- con would inherit two methods init and test
con.init ("yoururl");

Lets look at Crockford

//-------------------
//---- Class signalr - Crockford 
//-------------------

//-- signalr is here not the constructor, it's a normal function with a return value and setted prototype, the constructor becomes init which is defined in the signalr prototype
var signalr=function (url) 
    {
    return new signalr.prototype.init (url);
    }

//--prototype
//-----------

   //-- constructor
signalr.prototype.init=function (url)
    {
    this.url=url;
    }

signalr.prototype.test=function () {alert ("test");}
signalr.prototype.init.prototype=signalr.prototype       //- with this line, the prototype of the init method which is the constructor of our instances is linked to the prototype signalR so all instances would inherit the properties and methods defined in the signalR prototype

//-------------------
//---- Class signalr -- END
//-------------------

so to generate a new instance of this class we can write shortly the following to achieve the same like above.

var con=signalr ("yourURL");                //--- con inherits all the methods and properties of signalr.prototype with one line

seems that crockford is lazy to write lines, i'm thinking about pratical examples. but i think the whole thing is nothing exciting

查看更多
登录 后发表回答