代码之家  ›  专栏  ›  技术社区  ›  Alterlife

向对象添加动态函数

  •  0
  • Alterlife  · 技术社区  · 14 年前

    我正试着让它工作,但它没有:

    var i; 
    
    i.test = function() { 
        alert("hello"); 
    }
    
    i.test();
    

    missing } in XML expression
    alert("hello"); 
    ---------------^
    

    3 回复  |  直到 14 年前
        1
  •  4
  •   slebetman    14 年前

    你的 i undefined 对象,该对象在Firefox中恰好是只读的。您需要:

    var i = {}; //init to empty object
    

    那么一切都会好起来的。

        2
  •  0
  •   Guffa    14 年前

    不能将函数添加到未定义的值,需要创建实际对象:

    var i = {};
    

    i.test = function() { 
      alert("hello"); 
    };
    
        3
  •  0
  •   Matthew Flaschen    14 年前
    var i = {};
    i.test = function() { 
        alert("hello"); 
    };
    

    你有两个不同的问题。你没有初始化 i