В основном я искал возможность присоединять методы к исполняемой функции при использовании метода-прототипа 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, вы можетене возвращайте отдельное значение.
Любое объяснение или соображения были бы великолепны!