【问题标题】:Triple nested object functions js三重嵌套对象函数js
【发布时间】:2016-05-31 15:38:40
【问题描述】:

我有一个主要由函数/方法组成的对象,就像这样(应该可以工作!):

function thing1(){
    this.thing2 = function(){
        this.thing3 = function(){
            alert();
        }
    }
}

但是

当我打电话给thing1.thing2.thing3()时,我得到了

无法读取未定义的属性“thing3”

完整的伪代码:

function thing1(){
    this.thing2 = function(){
        this.thing3 = function(){
            alert();
        }
    }
}

var foo = new thing1();
foo.thing2.thing3();

【问题讨论】:

  • "应该可以工作!" - 不。你写的可以调用为var o = new thing1(); o.thing2(); o.thing3()

标签: javascript function object


【解决方案1】:

thing2 不返回任何导致返回 undefined 的内容。

如果要写链式函数,需要返回this

function thing1() {
    this.thing2 = function() {
        this.thing3 = function() {
            alert();
        }
        return this; // chained
    }
}

一般来说,如果您打算将函数原型用作构造函数,最好将方法分配给函数原型。您仍然可以在原型上链接函数。

function thing1() {
}

thing1.prototype.thing2 = function() {
  return this; // chained
};

thing1.prototype.thing3 = function() {
  alert('thing3');
  return this; // you can make this one chained as well, if you like
};

var t = new thing1();
t.thing2().thing3().thing2().thing3();

如果您只想创建一个不需要括号的基本链,您可以创建一个单独的getter function

function thing1() {
}

Object.defineProperty(thing1.prototype, 'thing2', {
  get: function() {
    return this;
  }
});

thing1.prototype.thing3 = function() {
  alert('thing3');
  return this;
};

var foo = new thing1();
foo.thing2.thing3().thing2.thing3();

【讨论】:

  • ...并且您不应该在任何其他方法(除了构造函数)中创建方法。
  • @Bergi 对。当您输入时,我正在更新;)
【解决方案2】:

那些是构造函数:

function thing1(){
    this.thing2 = function(){
        this.thing3 = function(){
            alert();
        }
    }
}

(new (new thing1()).thing2()).thing3()

如果你想调用thing1.thing2.thing3(),你应该这样格式化它:

function thing1(){
    this.thing2 = {
        thing3: function(){
            alert();
        }
    }
}

var foo = new thing1();

foo.thing2.thing3()

【讨论】:

  • 他们不必是构造函数。仅仅因为您为 this 分配了一个新属性并不一定意味着它是一个构造函数(尽管这通常是正确的)。
  • 好的,我将如何构造它们与父构造?所以我可以打电话给 thing1.thing2.thing3() 吗?我会摆脱 function(){} 部分并以某种方式将其全部放入变量中吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-27
  • 2018-01-04
  • 2020-06-29
  • 2018-04-02
相关资源
最近更新 更多