如何在另一个原型中创建可调用原型方法

How can I create a callable prototype method within another prototype

我正在尝试在对象原型中构建一个小型函数库。我以前只是将我的辅助函数作为全局函数,但是我正在尝试迁移到更独立的东西。

无论如何,我的原型包装器看起来像这样;

Q.fn = jHelper.prototype = {

    // helper functions
    addClass: function() {}, //...
    removeClass: function() {}, //...  
    // etc..

    // I want to add a child prototype method here that can be called
    Parent: function() {
        child: function(args) {
           console.log(args);
        }
    }

}

Q.Parent.child("test");

问题是我无法在 "Parent" 中调用函数。如何设置它以便我可以添加子函数作为 "Parent" 的原型?

您的 Parent 指向一个函数,并且有一个指向函数的标签。

它需要看起来像这样...

Parent: {
    child: function(args) {
       console.log(args);
    }
}

这也假设 Q.fn 指向 Q.prototype


I want "child" to be a prototype method of "Parent"

您需要像普通原型一样设置它。

您可以(如果您的目标支持__proto__)像这样直接设置...

Parent.__proto__ = { child: function() { } };

jsFiddle.

这意味着 Parent 的原型链(注意:不要给它一个大写字母,因为这是构造函数的约定)将如下所示:Parent -> Objectchild -> Object.prototype.

Object.prototype是行尾,你可以通过评估({}).__proto__ === Object.prototype.

看到这一点