javascript:作为对象或函数传递

前端之家收集整理的这篇文章主要介绍了javascript:作为对象或函数传递前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我的问题很奇怪,它与我在jQuery中看到的东西有关,但到目前为止我一直无法重新创建它.

在jQuery中你可以这样做

  1. jQuery('div').append

要么

  1. jQuery.ajax

我正在制作的应用程序需要类似的语法,我注意到你使用新的喜欢

  1. var that=new function(){
  2. }

你可以用这个来调用函数,没有(),但在某些情况下我会需要它.

原因是我需要选择一个dom元素,就像jQuery一样.

  1. that('[data-something="this"]').setEvent('click',functin(){})

有些人自动这样做:

  1. that.loadIt('this','[data-something="that"]')

这样做的原因是dom元素在外部加载并被推送,然后脚本在继续之前等待它准备就绪.这样做对我来说无论如何似乎是最干净的方式来获得这个功能(我编写一个完整的javascript框架,所以我避免库来保持脚本快速)

最佳答案
功能是对象.

只需摆脱新的,并直接添加属性.

  1. var that = function() {
  2. // do some work
  3. }
  4. that.loadit = function() {
  5. // do other work
  6. }

既然你正在尝试实现像jQuery那样的东西,那么就把它调用一个构造函数.

  1. ;(function(global) {
  2. // function to be publicly exposed
  3. var that = function(foo,bar) {
  4. return new MyLibrary(foo,bar);
  5. }
  6. // publicly expose the function
  7. global.that = that;
  8. // use the function as a namespace for utilities
  9. that.loadit = function() {
  10. // do other work
  11. }
  12. // The actual constructor function,like the internal jQuery constructor
  13. MyLibrary(foo,bar) {
  14. // constructor function
  15. }
  16. // Prototypal inheritance of objects created from the constructor
  17. MyLibrary.prototype.setEvent = function() {
  18. // do some work
  19. return this; // allows for method chaining
  20. };
  21. MyLibrary.prototype.otherMethod = function() {
  22. // do something else
  23. return this; // allows for method chaining
  24. };
  25. })(this);

猜你在找的jQuery相关文章