函数引用在js中是如何工作的



最近我一直在尝试将pixi.js用于一些有趣的项目,但我遇到了一个我根本不理解的概念。引用一些代码:

PIXI.loader
.add([
"images/one.png",
"images/two.png",
"images/three.png"
])
.on("progress", loadProgressHandler)
.load(setup);
function loadProgressHandler(loader, resource) {
console.log(`loading: ${resource.url}`);
};

既然我们只在事件侦听器中传递对函数的引用,那么这些参数(加载器、资源(是如何传递给函数的?有人能在这个概念下展示一个通用的实现吗?

假设我们有一个名为callMe的函数,它只打印给定的数字:

function callMe(number) {
console.log(`I'm number: ${number}`);
}
callMe(2);

我们可以为同一函数创建一个新变量,并调用新创建的变量。这是可能的,因为它指向的是我们之前创建的相同函数。

const callMeAswell = callMe;
callMe(3);
callMeAswell(4);

简而言之,这就是PIXI加载程序内部发生的事情,只是它存储在其他地方供您使用。让我们创建一个类来存储数字和我们想要调用的函数:

function SomeLoader(){
this.numbers = []; // list of numbers we want to store for later usage
this.func = null; // function that we want to call when we're done loading
}
SomeLoader.prototype.add = function(number) {
this.numbers.push(number); // add the number to the list of numbers
}
SomeLoader.prototype.on = function(func) {
this.func = func; // just store the function for now, but don't do anything with it
}
SomeLoader.prototype.pretendToLoad = function() {
for(const number of this.numbers) {
this.func(number); // now we're going to call the function that we've stored (callMe in the example below)
}
}
const loader = new SomeLoader();
loader.add(5);
loader.add(6);
loader.on(callMe);
loader.pretendToLoad();

或者流利地说:

function SomeLoader(){
this.numbers = [];
this.func = null;
}
SomeLoader.prototype.add = function(number) {
this.numbers.push(number);
return this;
}
SomeLoader.prototype.on = function(func) {
this.func = func;
return this;
}
SomeLoader.prototype.pretendToLoad = function() {
for(const number of this.numbers) {
this.func(number);
}
}
new SomeLoader()
.add(7)
.add(8)
.on(callMe)
.pretendToLoad();

看起来和PIXI装载机几乎一样,不是吗?:(

当函数被调用时,参数会被传递给它。

调用该函数的代码不是问题所在。它是在on函数后面的某个地方完成的。

简言之:和正常情况一样,你只是没有看到它发生的地方。

const show = value => console.log(value);
const call_callback_with_hello_world = callback => callback("Hello, world");
call_callback_with_hello_world(show);

@Quentin所说的是正确的,但除此之外。。。

该实现下面的一个通用概念被称为回调,看起来是这样的:

function Loop(callback, index){
	callback(index);
}
function CallbackFunction(val){
	console.log(val)
}
for(var i = 0; i < 5; i++){
	Loop(CallbackFunction, i);
}

最新更新