我已经been watching this video Damian说Crockford称之为:“超级构造模式”
代码示例:(来自视频)
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;
现在,我用谷歌搜索了Crockford和超级构造函数,但我能找到的只是Object.create
的实现:
我非常清楚地了解:(也是它的问题)
function create(o)
{
function f(){};
f.prototype=o;
return new f();
}
但我仍然不知道它是如何相关的:
问题:
答案 0 :(得分:3)
让我们在普通类中看到构造函数和原型
//-------------------
//---- Class signalr
//-------------------
//-- constructor
var signalr=function () {}
//--prototype
signalr.prototype.init=function (url)
{
this.url=url;
}
signalr.prototype.test=function () {alert ("test");}
//-------------------
//---- Class signalr -- END
//-------------------
因此要生成此类的新实例,我们必须编写以下内容。
var con=new signalr (); //--- con would inherit two methods init and test
con.init ("yoururl");
让我们看看克罗克福德
//-------------------
//---- 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
//-------------------
所以为了生成这个类的新实例,我们可以写下以下内容以实现与上面相同的内容。
var con=signalr ("yourURL"); //--- con inherits all the methods and properties of signalr.prototype with one line
似乎crockford懒得写行,我正在考虑实际的例子。但我认为整件事情并不令人兴奋