4

我将类或 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);
}
4

2 回答 2

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);
于 2013-07-31T20:53:36.273 回答
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');
}

输出:SampleHI

于 2021-01-05T15:33:17.043 回答