如何将实例函数传递给外部函数

how do you pass an instance function to an outside function?

本文关键字:函数 外部 实例      更新时间:2023-09-26

假设我有。我在文件file1.js中有以下内容:

//constructor
function Blah(){
    this.string = "hello there agent ";
}
//'method'
Blah.prototype.greeting = function(num){
    return  this.string + num;
}

然后在一个名为file2.js的文件中,我有如下内容:

function combine(num,funct){
    return funct(num);
}

最后,在名为file3的html文件中,我有这个:

var bond = new Blah();
document.write(combine(007,bond.greeting));

我实际上正在进入"greeting"方法,但由于某种原因,返回值不是字符串,而是不是NaN。知道为什么吗?greeting()方法似乎在适当的时间运行。然而,尽管如此,007似乎还是被解读为NaN。再说一遍,有什么建议可以引起这种情况吗?

Thanks a bunch in advance

首先,根据您如何调用greeting方法,this值将会不同。如果你把它叫做bond.greeting(num)那么this就是bond。如果像funct(num)那样调用它,其中functbond.greeting,那么this将是全局对象。在传递函数时需要永久绑定this,以便无论如何调用该函数都保持其值。

第二,007 === 7。如果您想按字面意思打印007,那么您应该使用字符串:

combine('007', bond.greeting.bind(bond));

请记住,this取决于函数如何被调用,它是动态的,并且在运行时解析,除非您之前绑定它,就像我们上面所做的那样。

您正在体验this关键字的特殊特性。

基本上,this解析为您调用函数的任何内容。在您的示例中,您从全局作用域通过func()调用它,这使得this == window。(通过bond.greeting()调用它就是this == bond)

要解析,这要么bind函数,要么强制解析:

// note that this method requires a shim for IE 8 and older
document.write(combine(007,bond.greeting.bind(bond)));

function combine(num, obj, funct){
    // since funct is being called from obj, `this` == obj within the function
    return obj[funct](num);
}
document.write(combine(007,bond, 'greeting'));    

您遇到的问题是,当您将函数作为参数传递时,它是按值传递的,然后您丢失了对具有元素string = "hello there agent ";的对象的引用,当函数执行时,它执行不存在于函数内的"this.string",它返回undefined。这是一个范围问题。

使其工作良好的解决方案是传递对象bond的引用。

function combine(num,obj){
    return obj.greeting(num);
}
combine("007",bond); // returns "hello there agent 007"

1) NaN是"非数字"错误。试着用引号把007括起来2)你需要file2.js还是不需要?

var bond = new Blah();
document.write(bond.greeting("007"));