基本上我在寻找能够在使用javascript原型方法时将方法附加到可执行函数的能力。下面的代码演示了我想要的和我正在寻找的功能,但它真的是一个黑客。注意我有一个有效的这个对象来附加变量以及main和init函数。
function create(){
var $this = {},
main = function(){
prototype.main.apply($this,arguments);
};
prototype.init.apply($this,arguments);
//Add additional prototype methods by brute force, ugly
for(i in prototype)-function(i){
main[i]=function(){
prototype[i].apply($this,arguments);
}
}(i);
return main;
};
var prototype = {
//called when you create the object
init:function(text){
console.log('init');
this.text = text;
},
//called when you call the object
main:function(){
console.log('main');
console.log(this);
},
method:function(){
console.log(this.text);
}
};
//create returns a function that also has methods
//the below line will call the init method
var fun = create('some variables');
//call main function
fun();
//call methods
fun.method();
我担心我可能会遗漏一些明显的东西。
这是与上面相同的功能,而是扩展了全局函数原型。
扩展全局属性是不好的做法,所以我正在寻找替代解决方案。
Function.prototype = {
//called when you create the object
init:function(text){
console.log('init');
this.text = text;
},
//called when you call the object
main:function(){
console.log('main');
console.log(this);
},
method:function(){
console.log(this.text);
}
};
function create(){
var ret = function(){
ret.main.call(main);
};
ret.init.apply(main,arguments);
return ret;
};
//create returns a function that also has methods
//the below line will call the init method
var fun = create('some variables');
//call main function
//fun();
//call methods
fun.method();
同样明显的一点是,您似乎无法使用典型的新对象方法,因为如果您调用new,则无法返回单独的值。
任何解释或考虑都会很棒!
答案 0 :(得分:1)
您可以将原型函数放入“构造函数”主体中。从技术上讲,这是您目前正在做的事情,但明确定义它们而不是使用辅助方法更加清晰。然后,您可以使用以下公共和私有变量和方法模式进一步简化代码:
function Fun(text) {
// This is the main function
var fn = function () {
return 'main';
};
// Attach public variables and methods
fn.publicVariable = 'public';
fn.publicMethod = function () {
return text; // text is a "private variable"
};
// Do whatever initialization
console.log('init');
// Return the main function
return fn;
}
var fun = Fun('this is some text'); // "init"
fun() // "main"
fun.publicMethod() // "this is some text"
console.log(fun.publicVariable); // "public"
console.log(fun.text); // undefined
答案 1 :(得分:0)
通过“JavaScript原型方法”,您的意思是使用Function.prototype
属性来实现继承吗?或者您只是尝试创建具有初始化程序和附加方法的函数?
你的例子是后者,所以我会假设你正在寻找的东西。这会做你想要的吗?
function create(text)
{
var main = function()
{
console.log('main');
console.log(this);
}
var init = function()
{
console.log('init');
main.text = text;
}
main.method = function()
{
console.log(main.text);
}
init();
return main;
}
//the following line will call init
var fun = create('some variables');
//call main
fun();
//call methods
fun.method();