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

How can I create a callable prototype method within another prototype

本文关键字:原型 调用 方法 创建 另一个      更新时间:2023-10-08

我正在尝试在对象原型中构建一个小型函数库。我以前只是把我的助手函数作为全局函数抛出,但我正试图迁移到更自我包含的东西。

不管怎样,我的原型包装看起来是这样的;

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


我希望"child"是"Parent"的原型方法

你需要把它设置成一个正常的原型。

你可以(如果你的目标支持__proto__)直接这样设置…

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

jsFiddle。

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

Object.prototype是行的末尾,您可以通过评估({}).__proto__ === Object.prototype来看到这一点。