简体   繁体   中英

Javascript function with prototype within parent function prototype

Is this even possible?

function foo() {
    // do stuff
}
foo.prototype = {
    // stuff...
    bar: function() {
        // do some things with this, where this refers to foo
    },
    bar.prototype: {
        // set some definitions for bar to work with.
        // Where does "this" go and what does it refer to?
    }
}

No. You'd need to use

function bar() {...}
bar.prototype = {...};
function foo() {...}
foo.prototype.bar = bar;

Although this won't work. There is no reason to put the bar constructor on foo s prototype, because when instantiating bar objects by using new ((new foo()).bar)() , there will be no reference to the foo instance. You could equally use new foo.prototype.bar() .

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