簡體   English   中英

JavaScript:訪問嵌套對象

[英]JavaScript: Accessing Nested Objects

代碼看起來像這樣

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

    }}}

var Control = new Scripts();

現在,當我說Control.FindById(“ T1”)。value()時。 我無法獲取textInput(“ T1”)的值。

看來您的代碼要復雜得多;-)

我個人將以這種方式編寫(未經測試):

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

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

現在, findById()在節點上關閉並返回一個可以返回其值的接口。

另外,您的想法聽起來很像Singleton,因此您甚至不需要額外的Scripts構造函數:

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

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

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

嘗試這個:

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

您沒有關閉最后一個“}” :-)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM