2012-06-13 209 views
1

的代码看起来像这样的JavaScript:访问嵌套对象

function Scripts() {this.FindById = function (id) { 
    this.FindById.constructor.prototype.value = function() { 
     return document.getElementById(id).value; 

    }}} 

var Control = new Scripts();

现在,当我说Control.FindById( “T1”)值()。我无法获得textInput(“T1”)的值。

+1

该代码是...奇怪。 – Pointy

回答

1

看来,你的代码是比较复杂那么一点应该是;-)

个人而言,我会写这样(未测试):

function Scripts() { 
    this.findById = function(id) { 
    var el = document.getElementById(id); 

    return { 
     value: function() { 
     return el.value; 
     } 
    } 
    } 
} 

findById()现在关闭了一节点并返回一个可以返回其值的接口。

而且,你的想法听起来很像单例,所以你甚至不需要额外的Scripts构造:

var Control = { 
    findById: function(id) { 
     var el = document.getElementById(id); 

     return { 
      value: function() { 
       return el.value; 
      } 
     } 
    } 
} 

工作例如:http://jsfiddle.net/YYkD7/

+0

对不起,我的错误是返回document.getElementById(id).value。我不知道如何“=”进来之间 – Rakesh

+0

它力气工作的情况下:( – Rakesh

+0

@Rakesh很抱歉听到,但这里有一个工作小提琴:http://jsfiddle.net/YYkD7/ –

0

试试这个:

function Scripts() {this.FindById = function (id) { 
    this.FindById.constructor.prototype.value = function() { 
     return document.getElementById(id).value 
    }}} 

您没有关闭最后的“}”:-)

+0

“}”我错过了这里。 – Rakesh

+0

好吧,没关系吧:) – Anonymous