gpt4 book ai didi

Javascript 的 super 构造函数 - 说明?

转载 作者:行者123 更新时间:2023-11-29 19:40:41 24 4
gpt4 key购买 nike

我已经 been watching this video Damian 说 Crockford 称之为:“ super 构造函数模式”

代码示例:(来自视频)

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;

现在,我用 google 搜索了 Crockford 和 super 构造函数但是我所能找到的只是Object.create 的实现:

我理解的很清楚:(也是陷阱)

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

但我仍然不明白它是如何关联的:

问题:

  • 到底是什么(在视频中)- 他试图通过使用此模式来解决什么问题? (也将不胜感激小代码示例)。

最佳答案

让我们看看带有构造函数和原型(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
//-------------------

因此要生成此类的新实例,我们必须编写以下内容。

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懒得写台词,我在想实际的例子。但我认为整件事并不令人兴奋

关于Javascript 的 super 构造函数 - 说明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23184344/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com