我知道可以添加到函数的原型(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)有些误解。
给定一个函数 Foo
,Foo.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/