我将类或var对象中的函数作为参数传递给另一个函数。 从类中接收函数的函数执行该函数。 它可以正常工作,但是类的功能从类中调用另一个函数。 控制台输出错误,即类函数中调用的函数未定义。
以下可能会更好地说明
//the class variable in someClass.js
function(params...){
getSomethingInClass: function(){
// return some variable
}
functionThatIsPassed: function(arg){
var theCalledFunction = getSomethingInClass();
//do something with theCalledFunction
}
}
//SOME WHERE ELSE in another function in another file
OtherFunction: function(){
//someClass is a variable being used here
FunctionThatTakesFunction(this.someClassVar.functionThatIsPassed);
}
//FunctionThatTakesFunction is implemented in another file
FunctionThatTakesFunction(callbackFun){
callbackFun(someArg);
}
如果我将其更改为传递整个对象someClass对象,则上述操作将起作用。传递对象是一种糟糕的编程习惯,因为FunctionThatTakesFunction需要知道其参数的功能 例如
//THIS WORKS!
//other stuff is same
//SOME WHERE ELSE in another function in another file
OtherFunction: function(){
//someClass is a variable being used here
FunctionThatTakesFunction(this.someClassVar);
}
//FunctionThatTakesFunction is implemented in another file
FunctionThatTakesFunction(object){
object.functionThatIsPassed(someArg);
}
答案 0 :(得分:1)
以下是将函数传递给另一个函数的一些示例:(小提琴:http://jsfiddle.net/FvyUQ/4/)
function Cat() {
this.myMeow = 'Mrrow';
this.scratch = function() {
console.log('Scritchey-scratch.');
}
}
Cat.prototype.meow = function() {
console.log(this.myMeow);
}
Cat.prototype.jump = function() {
console.log('The cat jumped and said ' + this.myMeow + '!');
}
function test(fn) {
fn();
}
function callPrototype(fn, context) {
fn.call(context);
}
var myCat = new Cat();
test(myCat.scratch);
test(myCat.meow);
test(myCat.jump);
test(Cat.prototype.jump);
callPrototype(Cat.prototype.jump, myCat);
答案 1 :(得分:0)
我使用闭包:
class Sample() {
constructor() {
this.id = 'Sample';
}
method(text) {
console.log(this.id + text)
}
getMethod() {
const ref = this;
return function(text) {
ref.method(text);
}
}
}
其他地方:
someFunc() {
const sample = new Sample();
useFunc(sample.getMethod());
}
useFunc(func) {
func('HI');
}
输出: 样本HI