Javascript function with prototype within parent function prototype

Deadly 提交于 2019-12-31 06:58:29

问题


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?
    }
}

回答1:


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 foos 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().



来源:https://stackoverflow.com/questions/11146820/javascript-function-with-prototype-within-parent-function-prototype

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!