2011-02-09 90 views
2

比方说,我有一个函数/值的对象。我对基于调用行为的重载感兴趣。我可以用一个函数重载一个对象吗?

例如,下面这段代码演示了我想要做的事情。

var main_thing = { 
    initalized: false, 
    something: "Hallo, welt!", 
    something_else: [123,456,789], 
    load: { 
     sub1 : function() { 
      //Some stuff 
     }, 
     sub2 : function() { 
      //Some stuff 
     }, 
     all  : function() { 
      this.sub1(); 
      this.sub2(); 
     } 
    } 
    init: function() { 
     this.initalized=true; 
     this.something="Hello, world!"; 
     this.something_else = [0,0,0]; 
     this.load(); //I want this to call this.load.all() instead. 
    } 
} 

这个问题对我来说是main_thing.load被分配到一个对象,并呼吁main_thing.load.all()会调用该对象(()运营商)的内部功能。我能做些什么来设置我的代码,以便我可以使用main_thing.load作为访问对象,并且main_thing.load()执行一些代码?或者至少,类似的行为。

基本上,这与其他语言中不需要调用main_thing.constructor()的默认构造函数类似。

如果这是不可能的,请详细解释一下。

+0

你描述听起来像一个构造函数,但你将其形容为超载。我在这里看不到任何重载函数。 – 2011-02-09 15:21:50

+0

函数是对象,因此您可以将“子函数”设置为函数的属性。在`main_thing.load.all`中顺便说一下`this`并不是指`main_thing`,而是指向`main_thing.load`。 – 2011-02-09 15:23:57

+0

我可能会误解 - 但如果你添加一个var loadfunctions = {sub1:function(){..},sub2 ...},然后重写你的负载到类似load:function(switch){if(!开关){loadfunctions.all; }其他...等 – Prescott 2011-02-09 15:28:45

回答

3

汤姆一样涂说,函数是对象,并且可以有属性...

var main_thing = { 

    // load will be set to the result of this anonymous function 
    // which is a function with 2 extra properties set for the other functions   
    load: function() { 
     // create what will be the load() function and store in "all" 
     var all = function() { 

       // When the function is actually executed these will have been assigned 
       all.load1(); 
       all.load2(); 
      }; 

     // set 2 properties for sub load functions 
     all.load1 = function() {}; 
     all.load2 = function() {}; 

     // return our function 
     return all; 
    }() 
} 

main_thing.load(); 
// or 
main_thing.load.load1(); 
main_thing.load.load2(); 
1

因为函数对象只是对象,所以引用函数的对象属性与引用普通对象的对象属性之间没有真正的区别。因此,“负载”只是外部对象的属性。

你可以做的是初始化“初始化”功能,里面的“负荷”的对象以使得其功能必须通过一个封闭访问外部对象的引用:

init: function() { 
    // whatever ... 

    var main_thing = this; 
    this.load.sub1 = function() { 
    main_thing.foo = "bar"; 
    }; 
    this.load.sub2 = function() { 
    main_thing.somethingElse(); 
    } 
} 

现在,这些功能中的“负荷“子对象有权访问该”main_thing“局部变量,它将引用外部对象。它们如何被调用并不重要。

另一种方法是在较新的浏览器中使用“bind()”工具,或者像Prototype of Functional这样的库提供。 (我个人只是偷绑定从Functional.js因为它是一个干净的实施)。

init: function() { 
    // ... 

    this.load.sub1 = function() { 
    this.foo = "bar"; 
    } .bind(this); 

} 

这种做法保证了无论“SUB1”怎么叫,它会永远拥有this绑定到参考当它(“sub1”,即)被定义时可用的外部对象。

0

你不能像这样重载JavaScript。 如果您main_thing.load功能,那么你可以调用main_thing.load(),您也可以访问内部的值,就像这样:

main_thing.load.a = 7; 
main_thing.load.b = "text"; 
main_thing.load.foo = function(x,y){alert("Hello, world "+x+", "+y); }; 
main_thing.load.foo(main_thing.load.a,main_thing.load.b); 

它提醒“你好,世界7文本”。

但main_thing.load本身可以用来存储一个函数,也可以用来存储其他一些数据,但不能同时存储。

相关问题