- (void)shootMissile {
//Send missile to delegate for storage
if ([delegate respondsToSelector:@selector(shootMissile)]) {
[delegate performSelector:@selector(shootMissile)];
}
}
委托函数意味着它委托给不同文件中的另一个函数。
我不确定我在javascript中遇到了类似的事情。
- (void)shootMissile {
//Send missile to delegate for storage
if ([delegate respondsToSelector:@selector(shootMissile)]) {
[delegate performSelector:@selector(shootMissile)];
}
}
委托函数意味着它委托给不同文件中的另一个函数。
我不确定我在javascript中遇到了类似的事情。
根据这个问题的第二个答案,委托如何在 Objective-C 中工作?:
代表是一种设计模式;没有特殊的语法或语言支持。
这种模式当然可以在 Javascript 中使用,其中函数是一等对象,因此可以作为参数传递给其他函数。
要在 JS 中重写您的示例:
function shootMissile(selector) {
if (selector.respondsTo(shootMissile)) {
selector.perform(shootMissile);
}
}
}
大概“选择器”是一个具有两个功能属性(即方法)的对象,称为“respondsTo”和“perform”。
上述更自然(或至少更实用)的版本是:
function shootMissile(canShootMissile, fireMissile, missile) {
if (canShootMissile(missile)) {
fireMissile(missile);
}
}
}
First a correction of the following assumption:
"delegate function means it's delegate to another function in a different file."
1) forget the "file" thing, it's all about context (a class instance for example)
2) It does not delegate to other function : function is delegated to another context (in Javascript, access the context with "this" keyword)
So in javascript, given the following function:
var shootMissile = function () {
this.missiles --;
};
We may delegate it to a bunch of different contexts (= objects), for example a boat:
var Boat = function () {
this.missiles = 10 ;
},
boatInstance = new Boat () ;
Or a plane:
var Plane = function () {
this.missiles = 5 ;
},
planeInstance = new Plane () ;
Finally the working example:
// planeInstance will have 4 missiles after call of delegated function
shootMissile.apply (planeInstance);
// boatInstance will have 9 missiles after call of delegated function
shootMissile.apply (boatInstance);
Hope this short explanation is sufficient for you.
等价物类似于匿名函数。我想也可以称为回调函数。