javascript - Javascript中原型(prototype)函数的原型(prototype)

标签 javascript prototype

我知道可以添加到函数的原型(prototype)中,这样

function main(){}
main.prototype.load = function()
{

}
...

并运行名为main.load的函数。

是否可以在该原型(prototype)中制作函数的原型(prototype)?换句话说,我可以做这样的事情:

main.prototype.get = function(){}
main.prototype.get.prototype.registration = function()
{
    // load registration info
}

并使用main.get.registration();调用该函数?

当我尝试执行此操作时,控制台中出现以下错误消息:

未捕获类型错误:对象函数 (){} 没有方法“注册”

编辑:我在调用new main();后执行此操作。所以我会做类似的事情

var thisMain = new main();
thisMain.get.registration();

最佳答案

我认为您对原型(prototype)有些误解。

给定一个函数 FooFoo.prototype 不是 Foo 对象的原型(prototype)。它是将分配给使用 new Foo() 创建的对象的原型(prototype)。例如:

// This is a constructor that creates objects whose prototype is Person.prototype
var Person = function(name) {
    this.name = name;
}
Person.prototype.sayHello = function() {
    console.log("Hello, my name is " + this.name);
}
var drew = new Person('Drew');
drew.sayHello();  // <-- Logs a message
drew.__proto__;   // <-- Not part of the Javascript spec, but it some browsers this is a reference to Person.prototype

您的 main.get.registration 可以在没有原型(prototype)的情况下实现:

main = function() {/* do stuff*/}
main.get = function() {/* this is a getter function? */}
main.get.registration = function() {/* I don't know what this does */}

您希望创建什么样的界面或 API?它是否涉及使用new创建对象?

更新:以下是实现您想要的功能的多种可能方法之一:

main = function() {
    // store a reference to this instance.
    var self = this;
    // Construct the get object.  It doesn't need to be a function because it's never invoked
    this.get = {};
    this.get.registration = function() {
        // Use self to refer to the specific instance of main you're interacting with.
        retrieveRegistrationFor(self); // <-- pseudo-code
    }
}

更新2:以下是如何使用构造函数构造get对象,允许您对所有内容使用原型(prototype)。我已将构造函数的名称大写,这是有助于区分普通函数/方法和构造函数的最佳实践。

// Constructor for the get object.  This is only ever invoked in Main's constructor.
Getter = function(mainInstance) {
    this.self = mainInstance;
}
Getter.prototype.registration = function() {
    retrieveRegistrationFor(this.self); // <-- pseudo-code
}

Main = function() {
    // Construct the get object and attach it to this object.
    this.get = new Getter(this);
}

正如其他答案所指出的,有很多方法可以在 Javascript 中构造对象。这完全取决于具体情况和您的个人编码风格。

关于javascript - Javascript中原型(prototype)函数的原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15286053/

相关文章:

javascript - 如何合并原型(prototype)对象中的默认选项

javascript - 增加引导复选框的大小

javascript - Backbone js MVC 语义建议

javascript - JavaScript 中的 987 和 (987) 有什么区别?

Javascript从构造函数内部的函数调用原型(prototype)函数

javascript - 为什么这些绑定(bind)函数的 "this"上下文在每个新实例中都相同?

Javascript:添加的功能不会出现在父对象上

javascript - 导出时如何更改 R highcharter 中菜单项的名称

javascript - chrome 开发者工具源代码

javascript - 神秘鼠标事件关闭 jQuery UI 对话框