Mod*_*ner 5 javascript frameworks anonymous function
我已经研究了几个星期的框架开发,并且我遇到了在lib开发世界中立即调用匿名函数的强烈建议和压力.
我永远无法让它工作,我找不到能够详细解释其背后的用途和逻辑的资源.
这是我目前所知道的:
我不仅要寻找一个详细的资源,而且要解释它背后的逻辑.因为我发现它非常不合逻辑.
这就是我所拥有的:
(function( window, document, undefined ) {
window.myThingy = myThingy;
var myThingy = function() {
};
myThingy.prototype = {
constructor: myThingy,
create: function( elementToBeCreated ) {
return document.createElement( elementToBeCreated );
}
};
})( window, document );
Run Code Online (Sandbox Code Playgroud)
然后,
myThingy().create("div");
Run Code Online (Sandbox Code Playgroud)
但它仍然说myThingy() [object]不是一个功能.
我究竟做错了什么?为什么我应该使用立即调用的函数而不仅仅是创建一个全局myThingy = function()对象?我为什么要使用window?
我知道网上有几个关于此的资源,但我无法理解它.其中一些进入细节,其中一些试图详细说明,但未能解释关键的东西.为什么在开发框架时如此强调?
别担心,我不是在试图"重新发明轮子",但我想尝试实际学习JavaScript,而不仅仅是预先打包的东西.
一个好的答案应该包含:
首先,当您尝试将函数分配给全局对象时,您尚未定义函数,因此它是未定义的:
window.myThingy = myThingy;
console.log(myThingy);//undefined
Run Code Online (Sandbox Code Playgroud)
myThingy您需要在定义后进行分配:
(function( window, document, undefined ) {
var myThingy = function() {
};
myThingy.prototype = {
constructor: myThingy,
create: function( elementToBeCreated ) {
return document.createElement( elementToBeCreated );
}
};
window.myThingy = myThingy;
})( window, document );
Run Code Online (Sandbox Code Playgroud)
好吧,接下来,你不能使用
myThingy.create("div");
Run Code Online (Sandbox Code Playgroud)
因为 myThingy 是一个函数而不是一个对象。new当向函数发出关键字时,函数对象就会被创建。您可以进行此更改以将函数转换为函数对象:
window.myThingy = new myThingy();//create a function object
Run Code Online (Sandbox Code Playgroud)
这种模式并不是所有框架的实现方式,但都是相似的。有时有更多的抽象。但是,进行这些更改将使您的方法发挥作用。
这是您的代码的演示: http: //jsfiddle.net/ZjRJW/
链接
以下是我最喜欢的一些:
http://ejohn.org/blog/simple-class-instantiation/
http://ejohn.org/blog/simple-javascript-inheritance/
http://jibbering.com/faq/notes/closures/
https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Details_of_the_Object_Model
http://javascript.crockford.com/prototypal.html
| 归档时间: |
|
| 查看次数: |
251 次 |
| 最近记录: |