简体   繁体   中英

Triple nested object functions js

I have an object mainly composed of functions/ methods, much like this (Which should work!):

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

But

When I call thing1.thing2.thing3() , I get

Cannot read property 'thing3' of undefined

complete pseudocode:

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

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

Those are constructors:

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

If you want to call thing1.thing2.thing3() you should format it like this:

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

thing2 doesn't return anything which results in returning undefined .

If you want to write chained functions, you need to return this :

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

Generally speaking, it's better to assign methods to a functions prototype if you intend to use it as a constructor. You can still chain functions on the prototype.

 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();

If you want to just create a basic chain without requiring parentheses, you could create a separate 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM